From ceffa84cdfde93536e88c973da3e8808af5a9063 Mon Sep 17 00:00:00 2001 From: christian Date: Mon, 4 Jul 2016 20:20:56 +0200 Subject: [PATCH 001/269] #3285 ModelNamePre- and Suffixes should not be applied to Types. --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 8 +++++++- .../io/swagger/codegen/languages/AbstractJavaCodegen.java | 5 +++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 786119b49f8..50961ef266d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1122,12 +1122,18 @@ public class DefaultCodegen { } /** - * Output the proper model name (capitalized) + * Output the proper model name (capitalized). + * In case the name belongs to the TypeSystem it won't be renamed. * * @param name the name of the model * @return capitalized model name */ public String toModelName(final String name) { + // Don't do any kind of renaming to language specific types + if(typeMapping.values().contains(name)) { + return name; + } + return initialCaps(modelNamePrefix + name + modelNameSuffix); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index c245125f80a..e1bc4f3a0d8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -343,6 +343,11 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toModelName(final String name) { + // Don't do any kind of sanitizing to Java types (e.g. BigDecimal) + if(typeMapping.values().contains(name)) { + return name; + } + final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); // camelize the model name From 41df857573d040fa08a1a19b8afd00a0e7da5539 Mon Sep 17 00:00:00 2001 From: christian Date: Wed, 6 Jul 2016 23:11:08 +0200 Subject: [PATCH 002/269] #3285 Check for typeMapper types inside getSwaggerType instead of toModelName --- .../io/swagger/codegen/DefaultCodegen.java | 5 ---- .../languages/AbstractJavaCodegen.java | 26 ++++++------------- 2 files changed, 8 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 50961ef266d..c122b14a7c9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1129,11 +1129,6 @@ public class DefaultCodegen { * @return capitalized model name */ public String toModelName(final String name) { - // Don't do any kind of renaming to language specific types - if(typeMapping.values().contains(name)) { - return name; - } - return initialCaps(modelNamePrefix + name + modelNameSuffix); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index e1bc4f3a0d8..04154c920f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -343,11 +343,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toModelName(final String name) { - // Don't do any kind of sanitizing to Java types (e.g. BigDecimal) - if(typeMapping.values().contains(name)) { - return name; - } - final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); // camelize the model name @@ -525,21 +520,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); - String type; + + // don't apply renaming on types from the typeMapping if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0 || - type.equals("Map") || type.equals("List") || - type.equals("File") || type.equals("Date")) { - return type; - } - } else { - type = swaggerType; + return typeMapping.get(swaggerType); } - if (null == type) { + + if (null == swaggerType) { LOGGER.error("No Type defined for Property " + p); } - return toModelName(type); + return toModelName(swaggerType); } @Override @@ -733,10 +723,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); op.path = sanitizePath(op.path); - + return op; } - + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze From 41a7aaffcc4c3cf42e96678f6c3cdf38acd778e2 Mon Sep 17 00:00:00 2001 From: Alec Hill Date: Mon, 17 Oct 2016 23:05:57 +0200 Subject: [PATCH 003/269] Support passing custom RequestInit options in typescript-fetch client, to enable fetch API specific options (eg including credentials, enabling CORS etc) --- .../resources/TypeScript-Fetch/api.mustache | 18 +- .../typescript-fetch/api.ts | 59 ++-- .../typescript-fetch/builds/default/api.ts | 322 +++++++++--------- .../typescript-fetch/builds/es6-target/api.ts | 322 +++++++++--------- .../builds/with-npm-version/api.ts | 322 +++++++++--------- .../tests/default/test/PetApi.ts | 76 +++-- .../tests/default/test/PetApiFactory.ts | 67 ++-- .../tests/default/test/StoreApi.ts | 32 +- .../tests/default/test/StoreApiFactory.ts | 24 +- 9 files changed, 659 insertions(+), 583 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index f1aa9e6c4bd..d89fa901bdb 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -14,7 +14,7 @@ const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -70,7 +70,7 @@ export const {{classname}}FetchParamCreactor = { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}): FetchArgs { + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any): FetchArgs { {{#allParams}} {{#required}} // verify required parameter "{{paramName}}" is set @@ -87,7 +87,7 @@ export const {{classname}}FetchParamCreactor = { "{{baseName}}": params.{{paramName}},{{/queryParams}} }); {{/hasQueryParams}} - let fetchOptions: RequestInit = { method: "{{httpMethod}}" }; + let fetchOptions: RequestInit = {{#supportsES6}}Object.{{/supportsES6}}assign({}, { method: "{{httpMethod}}" }, options); let contentTypeHeader: Dictionary; {{#hasFormParams}} @@ -131,8 +131,8 @@ export const {{classname}}Fp = { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }{{/hasParams}}): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { - const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params{{/hasParams}}); + {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }, {{/hasParams}}options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params, {{/hasParams}}options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -157,8 +157,8 @@ export class {{classname}} extends BaseAPI { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { - return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(this.fetch, this.basePath); + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params, {{/hasParams}}options)(this.fetch, this.basePath); } {{/operation}} }; @@ -175,8 +175,8 @@ export const {{classname}}Factory = function (fetch?: FetchAPI, basePath?: strin * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }{{/hasParams}}) { - return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(fetch, basePath); + {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { + return {{classname}}Fp.{{nickname}}({{#hasParams}}params, {{/hasParams}}options)(fetch, basePath); }, {{/operation}} } diff --git a/samples/client/petstore-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts index b439ec1d8ed..e935898c22f 100644 --- a/samples/client/petstore-security-test/typescript-fetch/api.ts +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -1,9 +1,9 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -31,11 +31,11 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r"; +const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -49,11 +49,11 @@ export class BaseAPI { } /** - * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r */ export interface ModelReturn { /** - * property description *_/ ' \" =end \\r\\n \\n \\r + * property description *_/ ' \" =end -- \\r\\n \\n \\r */ "return"?: number; } @@ -65,18 +65,18 @@ export interface ModelReturn { */ export const FakeApiFetchParamCreactor = { /** - * To test code injection *_/ ' \" =end \\r\\n \\n \\r - * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): FetchArgs { + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any): FetchArgs { const baseUrl = `/fake`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "test code inject */ ' " =end \r\n \n \r": params.test code inject * ' " =end rn n r, + "test code inject */ ' " =end -- \r\n \n \r": params.test code inject * ' " =end rn n r, }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -93,11 +93,11 @@ export const FakeApiFetchParamCreactor = { */ export const FakeApiFp = { /** - * To test code injection *_/ ' \" =end \\r\\n \\n \\r - * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params); + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -115,11 +115,26 @@ export const FakeApiFp = { */ export class FakeApi extends BaseAPI { /** - * To test code injection *_/ ' \" =end \\r\\n \\n \\r - * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }) { - return FakeApiFp.testCodeInjectEndRnNR(params)(this.fetch, this.basePath); + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any) { + return FakeApiFp.testCodeInjectEndRnNR(params, options)(this.fetch, this.basePath); } -} +}; + +/** + * FakeApi - factory interface + */ +export const FakeApiFactory = function (fetch?: FetchAPI, basePath?: string) { + return { + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any) { + return FakeApiFp.testCodeInjectEndRnNR(params, options)(fetch, basePath); + }, + } +}; diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index f37307f7352..020820e1ac2 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -35,7 +35,7 @@ const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -109,10 +109,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): FetchArgs { + addPet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -133,7 +133,7 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); @@ -141,7 +141,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = assign({ @@ -157,13 +157,13 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): FetchArgs { + findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "status": params.status, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -179,13 +179,13 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): FetchArgs { + findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "tags": params.tags, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -201,7 +201,7 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }): FetchArgs { + getPetById(params: { petId: number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); @@ -209,7 +209,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -225,10 +225,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): FetchArgs { + updatePet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -250,7 +250,7 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); @@ -258,7 +258,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -281,7 +281,7 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); @@ -289,7 +289,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -316,8 +316,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params); + addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -334,8 +334,8 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -351,8 +351,8 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -368,8 +368,8 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -385,8 +385,8 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -402,8 +402,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -421,8 +421,8 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -440,8 +440,8 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -463,8 +463,8 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(this.fetch, this.basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** * Deletes a pet @@ -472,40 +472,40 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(this.fetch, this.basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(this.fetch, this.basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(this.fetch, this.basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** * Updates a pet in the store with form data @@ -514,8 +514,8 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** * uploads an image @@ -524,8 +524,8 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -539,8 +539,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(fetch, basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(fetch, basePath); }, /** * Deletes a pet @@ -548,40 +548,40 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(fetch, basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(fetch, basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(fetch, basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(fetch, basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(fetch, basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** * Updates a pet in the store with form data @@ -590,8 +590,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(fetch, basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** * uploads an image @@ -600,8 +600,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(fetch, basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(fetch, basePath); }, } }; @@ -616,7 +616,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }): FetchArgs { + deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); @@ -624,7 +624,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -639,10 +639,10 @@ export const StoreApiFetchParamCreactor = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): FetchArgs { + getInventory(options?: any): FetchArgs { const baseUrl = `/store/inventory`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -658,7 +658,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }): FetchArgs { + getOrderById(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); @@ -666,7 +666,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -682,10 +682,10 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): FetchArgs { + placeOrder(params: { body?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -711,8 +711,8 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -727,8 +727,8 @@ export const StoreApiFp = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -744,8 +744,8 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -761,8 +761,8 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -784,31 +784,31 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(this.fetch, this.basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(this.fetch, this.basePath); } /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -822,31 +822,31 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(fetch, basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(fetch, basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(fetch, basePath); }, /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(fetch, basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(fetch, basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, } }; @@ -861,10 +861,10 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): FetchArgs { + createUser(params: { body?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -884,10 +884,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -907,10 +907,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): FetchArgs { + createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -930,7 +930,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): FetchArgs { + deleteUser(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); @@ -938,7 +938,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -954,7 +954,7 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): FetchArgs { + getUserByName(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); @@ -962,7 +962,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -979,14 +979,14 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): FetchArgs { + loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "username": params.username, "password": params.password, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1001,10 +1001,10 @@ export const UserApiFetchParamCreactor = { * Logs out current logged in user session * */ - logoutUser(): FetchArgs { + logoutUser(options?: any): FetchArgs { const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1021,7 +1021,7 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): FetchArgs { + updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); @@ -1029,7 +1029,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -1055,8 +1055,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params); + createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1072,8 +1072,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1089,8 +1089,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1106,8 +1106,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1123,8 +1123,8 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1141,8 +1141,8 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1157,8 +1157,8 @@ export const UserApiFp = { * Logs out current logged in user session * */ - logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1175,8 +1175,8 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1198,40 +1198,40 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(this.fetch, this.basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** * Logs user into the system @@ -1239,15 +1239,15 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(this.fetch, this.basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(this.fetch, this.basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(this.fetch, this.basePath); } /** * Updated user @@ -1255,8 +1255,8 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(this.fetch, this.basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1270,40 +1270,40 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(fetch, basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(fetch, basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(fetch, basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** * Logs user into the system @@ -1311,15 +1311,15 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(fetch, basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(fetch, basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(fetch, basePath); }, /** * Updated user @@ -1327,8 +1327,8 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(fetch, basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(fetch, basePath); }, } }; diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index fa7d5153c10..f58443103de 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -34,7 +34,7 @@ const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -108,10 +108,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): FetchArgs { + addPet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -132,7 +132,7 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); @@ -140,7 +140,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = Object.assign({ @@ -156,13 +156,13 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): FetchArgs { + findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "status": params.status, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -178,13 +178,13 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): FetchArgs { + findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "tags": params.tags, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -200,7 +200,7 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }): FetchArgs { + getPetById(params: { petId: number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); @@ -208,7 +208,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -224,10 +224,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): FetchArgs { + updatePet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -249,7 +249,7 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); @@ -257,7 +257,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -280,7 +280,7 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); @@ -288,7 +288,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -315,8 +315,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params); + addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -333,8 +333,8 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -350,8 +350,8 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -367,8 +367,8 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -384,8 +384,8 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -401,8 +401,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -420,8 +420,8 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -439,8 +439,8 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -462,8 +462,8 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(this.fetch, this.basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** * Deletes a pet @@ -471,40 +471,40 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(this.fetch, this.basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(this.fetch, this.basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(this.fetch, this.basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** * Updates a pet in the store with form data @@ -513,8 +513,8 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** * uploads an image @@ -523,8 +523,8 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -538,8 +538,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(fetch, basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(fetch, basePath); }, /** * Deletes a pet @@ -547,40 +547,40 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(fetch, basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(fetch, basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(fetch, basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(fetch, basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(fetch, basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** * Updates a pet in the store with form data @@ -589,8 +589,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(fetch, basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** * uploads an image @@ -599,8 +599,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(fetch, basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(fetch, basePath); }, } }; @@ -615,7 +615,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }): FetchArgs { + deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); @@ -623,7 +623,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -638,10 +638,10 @@ export const StoreApiFetchParamCreactor = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): FetchArgs { + getInventory(options?: any): FetchArgs { const baseUrl = `/store/inventory`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -657,7 +657,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }): FetchArgs { + getOrderById(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); @@ -665,7 +665,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -681,10 +681,10 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): FetchArgs { + placeOrder(params: { body?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -710,8 +710,8 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -726,8 +726,8 @@ export const StoreApiFp = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -743,8 +743,8 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -760,8 +760,8 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -783,31 +783,31 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(this.fetch, this.basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(this.fetch, this.basePath); } /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -821,31 +821,31 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(fetch, basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(fetch, basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(fetch, basePath); }, /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(fetch, basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(fetch, basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, } }; @@ -860,10 +860,10 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): FetchArgs { + createUser(params: { body?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -883,10 +883,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -906,10 +906,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): FetchArgs { + createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -929,7 +929,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): FetchArgs { + deleteUser(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); @@ -937,7 +937,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -953,7 +953,7 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): FetchArgs { + getUserByName(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); @@ -961,7 +961,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -978,14 +978,14 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): FetchArgs { + loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { "username": params.username, "password": params.password, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1000,10 +1000,10 @@ export const UserApiFetchParamCreactor = { * Logs out current logged in user session * */ - logoutUser(): FetchArgs { + logoutUser(options?: any): FetchArgs { const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1020,7 +1020,7 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): FetchArgs { + updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); @@ -1028,7 +1028,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = Object.assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -1054,8 +1054,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params); + createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1071,8 +1071,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1088,8 +1088,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1105,8 +1105,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1122,8 +1122,8 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1140,8 +1140,8 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1156,8 +1156,8 @@ export const UserApiFp = { * Logs out current logged in user session * */ - logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1174,8 +1174,8 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1197,40 +1197,40 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(this.fetch, this.basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** * Logs user into the system @@ -1238,15 +1238,15 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(this.fetch, this.basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(this.fetch, this.basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(this.fetch, this.basePath); } /** * Updated user @@ -1254,8 +1254,8 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(this.fetch, this.basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1269,40 +1269,40 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(fetch, basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(fetch, basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(fetch, basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** * Logs user into the system @@ -1310,15 +1310,15 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(fetch, basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(fetch, basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(fetch, basePath); }, /** * Updated user @@ -1326,8 +1326,8 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(fetch, basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(fetch, basePath); }, } }; diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index f37307f7352..020820e1ac2 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -35,7 +35,7 @@ const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -109,10 +109,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): FetchArgs { + addPet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -133,7 +133,7 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): FetchArgs { + deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); @@ -141,7 +141,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = assign({ @@ -157,13 +157,13 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): FetchArgs { + findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "status": params.status, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -179,13 +179,13 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): FetchArgs { + findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "tags": params.tags, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -201,7 +201,7 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }): FetchArgs { + getPetById(params: { petId: number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); @@ -209,7 +209,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -225,10 +225,10 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): FetchArgs { + updatePet(params: { body?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -250,7 +250,7 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): FetchArgs { + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); @@ -258,7 +258,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -281,7 +281,7 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): FetchArgs { + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); @@ -289,7 +289,7 @@ export const PetApiFetchParamCreactor = { const baseUrl = `/pet/{petId}/uploadImage` .replace(`{${"petId"}}`, `${ params.petId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; @@ -316,8 +316,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params); + addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -334,8 +334,8 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params); + deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -351,8 +351,8 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params); + findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -368,8 +368,8 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params); + findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -385,8 +385,8 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params); + getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -402,8 +402,8 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params); + updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -421,8 +421,8 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -440,8 +440,8 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -463,8 +463,8 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(this.fetch, this.basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** * Deletes a pet @@ -472,40 +472,40 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(this.fetch, this.basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(this.fetch, this.basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(this.fetch, this.basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(this.fetch, this.basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(this.fetch, this.basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** * Updates a pet in the store with form data @@ -514,8 +514,8 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(this.fetch, this.basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** * uploads an image @@ -524,8 +524,8 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(this.fetch, this.basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -539,8 +539,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }) { - return PetApiFp.addPet(params)(fetch, basePath); + addPet(params: { body?: Pet; }, options?: any) { + return PetApiFp.addPet(params, options)(fetch, basePath); }, /** * Deletes a pet @@ -548,40 +548,40 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }) { - return PetApiFp.deletePet(params)(fetch, basePath); + deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }) { - return PetApiFp.findPetsByStatus(params)(fetch, basePath); + findPetsByStatus(params: { status?: Array; }, options?: any) { + return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }) { - return PetApiFp.findPetsByTags(params)(fetch, basePath); + findPetsByTags(params: { tags?: Array; }, options?: any) { + return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** * 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 */ - getPetById(params: { petId: number; }) { - return PetApiFp.getPetById(params)(fetch, basePath); + getPetById(params: { petId: number; }, options?: any) { + return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** * Update an existing pet * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }) { - return PetApiFp.updatePet(params)(fetch, basePath); + updatePet(params: { body?: Pet; }, options?: any) { + return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** * Updates a pet in the store with form data @@ -590,8 +590,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }) { - return PetApiFp.updatePetWithForm(params)(fetch, basePath); + updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** * uploads an image @@ -600,8 +600,8 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { - return PetApiFp.uploadFile(params)(fetch, basePath); + uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + return PetApiFp.uploadFile(params, options)(fetch, basePath); }, } }; @@ -616,7 +616,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }): FetchArgs { + deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); @@ -624,7 +624,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -639,10 +639,10 @@ export const StoreApiFetchParamCreactor = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): FetchArgs { + getInventory(options?: any): FetchArgs { const baseUrl = `/store/inventory`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -658,7 +658,7 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }): FetchArgs { + getOrderById(params: { orderId: string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); @@ -666,7 +666,7 @@ export const StoreApiFetchParamCreactor = { const baseUrl = `/store/order/{orderId}` .replace(`{${"orderId"}}`, `${ params.orderId }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -682,10 +682,10 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): FetchArgs { + placeOrder(params: { body?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -711,8 +711,8 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params); + deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -727,8 +727,8 @@ export const StoreApiFp = { * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory(): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(); + getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { + const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -744,8 +744,8 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params); + getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -761,8 +761,8 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params); + placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -784,31 +784,31 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(this.fetch, this.basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(this.fetch, this.basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(this.fetch, this.basePath); } /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(this.fetch, this.basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(this.fetch, this.basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -822,31 +822,31 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }) { - return StoreApiFp.deleteOrder(params)(fetch, basePath); + deleteOrder(params: { orderId: string; }, options?: any) { + return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** * Returns pet inventories by status * Returns a map of status codes to quantities */ - getInventory() { - return StoreApiFp.getInventory()(fetch, basePath); + getInventory(options?: any) { + return StoreApiFp.getInventory(options)(fetch, basePath); }, /** * 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 */ - getOrderById(params: { orderId: string; }) { - return StoreApiFp.getOrderById(params)(fetch, basePath); + getOrderById(params: { orderId: string; }, options?: any) { + return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** * Place an order for a pet * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }) { - return StoreApiFp.placeOrder(params)(fetch, basePath); + placeOrder(params: { body?: Order; }, options?: any) { + return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, } }; @@ -861,10 +861,10 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): FetchArgs { + createUser(params: { body?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -884,10 +884,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): FetchArgs { + createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -907,10 +907,10 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): FetchArgs { + createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "POST" }; + let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -930,7 +930,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): FetchArgs { + deleteUser(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); @@ -938,7 +938,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "DELETE" }; + let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -954,7 +954,7 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): FetchArgs { + getUserByName(params: { username: string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); @@ -962,7 +962,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -979,14 +979,14 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): FetchArgs { + loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { "username": params.username, "password": params.password, }); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1001,10 +1001,10 @@ export const UserApiFetchParamCreactor = { * Logs out current logged in user session * */ - logoutUser(): FetchArgs { + logoutUser(options?: any): FetchArgs { const baseUrl = `/user/logout`; let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "GET" }; + let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); let contentTypeHeader: Dictionary; if (contentTypeHeader) { @@ -1021,7 +1021,7 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): FetchArgs { + updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); @@ -1029,7 +1029,7 @@ export const UserApiFetchParamCreactor = { const baseUrl = `/user/{username}` .replace(`{${"username"}}`, `${ params.username }`); let urlObj = url.parse(baseUrl, true); - let fetchOptions: RequestInit = { method: "PUT" }; + let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/json" }; @@ -1055,8 +1055,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params); + createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1072,8 +1072,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params); + createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1089,8 +1089,8 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params); + createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1106,8 +1106,8 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params); + deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1123,8 +1123,8 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params); + getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1141,8 +1141,8 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params); + loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1157,8 +1157,8 @@ export const UserApiFp = { * Logs out current logged in user session * */ - logoutUser(): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(); + logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1175,8 +1175,8 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params); + updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1198,40 +1198,40 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(this.fetch, this.basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(this.fetch, this.basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(this.fetch, this.basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(this.fetch, this.basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(this.fetch, this.basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** * Logs user into the system @@ -1239,15 +1239,15 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(this.fetch, this.basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(this.fetch, this.basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(this.fetch, this.basePath); } /** * Updated user @@ -1255,8 +1255,8 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(this.fetch, this.basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1270,40 +1270,40 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }) { - return UserApiFp.createUser(params)(fetch, basePath); + createUser(params: { body?: User; }, options?: any) { + return UserApiFp.createUser(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithArrayInput(params)(fetch, basePath); + createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** * Creates list of users with given input array * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }) { - return UserApiFp.createUsersWithListInput(params)(fetch, basePath); + createUsersWithListInput(params: { body?: Array; }, options?: any) { + return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** * Delete user * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }) { - return UserApiFp.deleteUser(params)(fetch, basePath); + deleteUser(params: { username: string; }, options?: any) { + return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** * Get user by user name * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }) { - return UserApiFp.getUserByName(params)(fetch, basePath); + getUserByName(params: { username: string; }, options?: any) { + return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** * Logs user into the system @@ -1311,15 +1311,15 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }) { - return UserApiFp.loginUser(params)(fetch, basePath); + loginUser(params: { username?: string; password?: string; }, options?: any) { + return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** * Logs out current logged in user session * */ - logoutUser() { - return UserApiFp.logoutUser()(fetch, basePath); + logoutUser(options?: any) { + return UserApiFp.logoutUser(options)(fetch, basePath); }, /** * Updated user @@ -1327,8 +1327,8 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }) { - return UserApiFp.updateUser(params)(fetch, basePath); + updateUser(params: { username: string; body?: User; }, options?: any) { + return UserApiFp.updateUser(params, options)(fetch, basePath); }, } }; diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts index 04b2c032a34..251c3f3a902 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApi.ts @@ -2,46 +2,62 @@ import {expect} from 'chai'; import {PetApi, Pet, Category} from 'typescript-fetch-api'; describe('PetApi', () => { - let api: PetApi; - let fixture: Pet = createTestFixture(); - beforeEach(() => { - api = new PetApi(); - }); + function runSuite(description: string, requestOptions?: any): void { - it('should add and delete Pet', () => { - return api.addPet({ body: fixture }).then(() => { - }); - }); + describe(description, () => { - it('should get Pet by ID', () => { - return api.getPetById({ petId: fixture.id }).then((result) => { - return expect(result).to.deep.equal(fixture); + let api: PetApi; + const fixture: Pet = createTestFixture(); + + beforeEach(() => { + api = new PetApi(); }); - }); - it('should update Pet by ID', () => { - return api.getPetById({ petId: fixture.id }).then( (result) => { - result.name = 'newname'; - return api.updatePet({ body: result }).then(() => { - return api.getPetById({ petId: fixture.id }).then( (result) => { - return expect(result.name).to.deep.equal('newname'); + it('should add and delete Pet', () => { + return api.addPet({ body: fixture }, requestOptions).then(() => { }); }); + + it('should get Pet by ID', () => { + return api.getPetById({ petId: fixture.id }, requestOptions).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return api.getPetById({ petId: fixture.id }, requestOptions).then( (result) => { + result.name = 'newname'; + return api.updatePet({ body: result }, requestOptions).then(() => { + return api.getPetById({ petId: fixture.id }, requestOptions).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return api.deletePet({ petId: fixture.id }, requestOptions); + }); + + it('should not contain deleted Pet', () => { + return api.getPetById({ petId: fixture.id }, requestOptions).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + return expect(err).to.exist; + }); + }); + }); - }); - - it('should delete Pet', () => { - return api.deletePet({ petId: fixture.id }); + } + + runSuite('without custom request options'); + + runSuite('with custom request options', { + credentials: 'include', + mode: 'cors' }); - it('should not contain deleted Pet', () => { - return api.getPetById({ petId: fixture.id }).then((result) => { - return expect(result).to.not.exist; - }, (err) => { - return expect(err).to.exist; - }); - }); }); function createTestFixture(ts = Date.now()) { diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts b/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts index 38acc214e21..be2b802c1e7 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/PetApiFactory.ts @@ -2,41 +2,56 @@ import {expect} from 'chai'; import {PetApiFactory, Pet, Category} from 'typescript-fetch-api'; describe('PetApiFactory', () => { - let fixture: Pet = createTestFixture(); - it('should add and delete Pet', () => { - return PetApiFactory().addPet({ body: fixture }).then(() => { - }); - }); + function runSuite(description: string, requestOptions?: any): void { - it('should get Pet by ID', () => { - return PetApiFactory().getPetById({ petId: fixture.id }).then((result) => { - return expect(result).to.deep.equal(fixture); + describe(description, () => { + + const fixture: Pet = createTestFixture(); + + it('should add and delete Pet', () => { + return PetApiFactory().addPet({ body: fixture }, requestOptions).then(() => { + }); }); - }); - it('should update Pet by ID', () => { - return PetApiFactory().getPetById({ petId: fixture.id }).then( (result) => { - result.name = 'newname'; - return PetApiFactory().updatePet({ body: result }).then(() => { - return PetApiFactory().getPetById({ petId: fixture.id }).then( (result) => { - return expect(result.name).to.deep.equal('newname'); + it('should get Pet by ID', () => { + return PetApiFactory().getPetById({ petId: fixture.id }, requestOptions).then((result) => { + return expect(result).to.deep.equal(fixture); + }); + }); + + it('should update Pet by ID', () => { + return PetApiFactory().getPetById({ petId: fixture.id }, requestOptions).then( (result) => { + result.name = 'newname'; + return PetApiFactory().updatePet({ body: result }, requestOptions).then(() => { + return PetApiFactory().getPetById({ petId: fixture.id }, requestOptions).then( (result) => { + return expect(result.name).to.deep.equal('newname'); + }); + }); + }); + }); + + it('should delete Pet', () => { + return PetApiFactory().deletePet({ petId: fixture.id }, requestOptions); + }); + + it('should not contain deleted Pet', () => { + return PetApiFactory().getPetById({ petId: fixture.id }, requestOptions).then((result) => { + return expect(result).to.not.exist; + }, (err) => { + return expect(err).to.exist; }); }); }); - }); - - it('should delete Pet', () => { - return PetApiFactory().deletePet({ petId: fixture.id }); + } + + runSuite('without custom request options'); + + runSuite('with custom request options', { + credentials: 'include', + mode: 'cors' }); - it('should not contain deleted Pet', () => { - return PetApiFactory().getPetById({ petId: fixture.id }).then((result) => { - return expect(result).to.not.exist; - }, (err) => { - return expect(err).to.exist; - }); - }); }); function createTestFixture(ts = Date.now()) { diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts index 420def0ab62..14b26e4f2d0 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApi.ts @@ -2,17 +2,31 @@ import {expect} from 'chai'; import {StoreApi} from 'typescript-fetch-api'; describe('StoreApi', function() { - let api: StoreApi; - - beforeEach(function() { - api = new StoreApi(); - }); - it('should get inventory', function() { - return api.getInventory().then((result) => { - expect(Object.keys(result)).to.not.be.empty; + function runSuite(description: string, requestOptions?: any): void { + + describe(description, () => { + let api: StoreApi; + const requestOptions: any = {credentials: 'include', mode: 'cors'} + + beforeEach(function() { + api = new StoreApi(); + }); + + it('should get inventory', function() { + return api.getInventory(requestOptions).then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + }); + } + + runSuite('without custom request options'); + + runSuite('with custom request options', { + credentials: 'include', + mode: 'cors' }); }); - diff --git a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts index c1d5560e2af..bef90b2a558 100644 --- a/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts +++ b/samples/client/petstore/typescript-fetch/tests/default/test/StoreApiFactory.ts @@ -2,11 +2,27 @@ import {expect} from 'chai'; import {StoreApiFactory} from 'typescript-fetch-api'; describe('StoreApiFactory', function() { - it('should get inventory', function() { - return StoreApiFactory().getInventory().then((result) => { - expect(Object.keys(result)).to.not.be.empty; + + function runSuite(description: string, requestOptions?: any): void { + + describe(description, () => { + + const requestOptions: any = {credentials: 'include', mode: 'cors'}; + + it('should get inventory', function() { + return StoreApiFactory().getInventory(requestOptions).then((result) => { + expect(Object.keys(result)).to.not.be.empty; + }); + }); + }); + } + + runSuite('without custom request options'); + + runSuite('with custom request options', { + credentials: 'include', + mode: 'cors' }); }); - From 23fee386f2d4cb3a43710ef8e4138011b8e1fdcc Mon Sep 17 00:00:00 2001 From: raj k Date: Wed, 19 Oct 2016 13:40:16 -0700 Subject: [PATCH 004/269] Vendor Mime-type support in retrofit2 --- .../io/swagger/codegen/CodegenOperation.java | 5 +- .../codegen/languages/JavaClientCodegen.java | 90 +- .../Java/libraries/retrofit2/api.mustache | 9 + .../languages/JavaClientCodegenTest.java | 79 ++ .../resources/2_0/petstore-vendor-mime.yaml | 1232 +++++++++++++++++ .../java/io/swagger/client/api/FakeApi.java | 5 +- .../java/io/swagger/client/api/PetApi.java | 8 +- 7 files changed, 1418 insertions(+), 10 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java create mode 100644 modules/swagger-codegen/src/test/resources/2_0/petstore-vendor-mime.yaml diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 501479955fd..1bd02c68d5d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -19,7 +19,7 @@ public class CodegenOperation { isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse, discriminator; - public List> consumes, produces; + public List> consumes, produces, prioritizedContentTypes; public CodegenParameter bodyParam; public List allParams = new ArrayList(); public List bodyParams = new ArrayList(); @@ -275,6 +275,8 @@ public class CodegenOperation { return false; if (nickname != null ? !nickname.equals(that.nickname) : that.nickname != null) return false; + if ( prioritizedContentTypes != null ? !prioritizedContentTypes.equals(that.prioritizedContentTypes) : that.prioritizedContentTypes != null ) + return false; return operationIdLowerCase != null ? operationIdLowerCase.equals(that.operationIdLowerCase) : that.operationIdLowerCase == null; } @@ -325,6 +327,7 @@ public class CodegenOperation { result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + (nickname != null ? nickname.hashCode() : 0); + result = 31 * result + (prioritizedContentTypes != null ? prioritizedContentTypes.hashCode() : 0); result = 31 * result + (operationIdLowerCase != null ? operationIdLowerCase.hashCode() : 0); return result; } 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 58286080a81..776d849f478 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 @@ -8,9 +8,12 @@ import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; +import java.util.regex.Pattern; public class JavaClientCodegen extends AbstractJavaCodegen { - @SuppressWarnings("hiding") + static final String MEDIA_TYPE = "mediaType"; + + @SuppressWarnings("hiding") private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; @@ -173,24 +176,73 @@ public class JavaClientCodegen extends AbstractJavaCodegen { List ops = (List) operations.get("operation"); for (CodegenOperation operation : ops) { if (operation.hasConsumes == Boolean.TRUE) { - Map firstType = operation.consumes.get(0); - if (firstType != null) { - if ("multipart/form-data".equals(firstType.get("mediaType"))) { - operation.isMultipart = Boolean.TRUE; - } + + if ( isMultipartType(operation.consumes) ) { + operation.isMultipart = Boolean.TRUE; + } + else { + operation.prioritizedContentTypes = prioritizeContentTypes(operation.consumes); } } if (operation.returnType == null) { operation.returnType = "Void"; } if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) - operation.path = operation.path.substring(1); + operation.path = operation.path.substring(1); } } } return objs; } + /** + * Prioritizes consumes mime-type list by moving json-vendor and json mime-types up front, but + * otherwise preserves original consumes definition order. + * [application/vnd...+json,... application/json, ..as is..] + * + * @param consumes consumes mime-type list + * @return + */ + static List> prioritizeContentTypes(List> consumes) { + if ( consumes.size() <= 1 ) + return consumes; + + List> prioritizedContentTypes = new ArrayList<>(consumes.size()); + + List> jsonVendorMimeTypes = new ArrayList<>(consumes.size()); + List> jsonMimeTypes = new ArrayList<>(consumes.size()); + + for ( Map consume : consumes) { + if ( isJsonVendorMimeType(consume.get(MEDIA_TYPE))) { + jsonVendorMimeTypes.add(consume); + } + else if ( isJsonMimeType(consume.get(MEDIA_TYPE))) { + jsonMimeTypes.add(consume); + } + else + prioritizedContentTypes.add(consume); + + consume.put("hasMore", "true"); + } + + prioritizedContentTypes.addAll(0, jsonMimeTypes); + prioritizedContentTypes.addAll(0, jsonVendorMimeTypes); + + prioritizedContentTypes.get(prioritizedContentTypes.size()-1).put("hasMore", null); + + return prioritizedContentTypes; + } + + private static boolean isMultipartType(List> consumes) { + Map firstType = consumes.get(0); + if (firstType != null) { + if ("multipart/form-data".equals(firstType.get(MEDIA_TYPE))) { + return true; + } + } + return false; + } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -245,4 +297,28 @@ public class JavaClientCodegen extends AbstractJavaCodegen { this.supportJava6 = value; } + final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application\\/json(;.*)?"); + final private static Pattern JSON_VENDOR_MIME_PATTERN = Pattern.compile("(?i)application\\/vnd.(.*)+json(;.*)?"); + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + */ + static boolean isJsonMimeType(String mime) { + return mime != null && ( JSON_MIME_PATTERN.matcher(mime).matches()); + } + + /** + * Check if the given MIME is a JSON Vendor MIME. + * JSON MIME examples: + * application/vnd.mycompany+json + * application/vnd.mycompany.resourceA.version1+json + */ + static boolean isJsonVendorMimeType(String mime) { + return mime != null && JSON_VENDOR_MIME_PATTERN.matcher(mime).matches(); + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 7682d27c9c8..3b32a240726 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -29,6 +29,15 @@ public interface {{classname}} { */ {{#formParams}}{{#-first}} {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{^formParams}} + {{#prioritizedContentTypes}} + {{#-first}} + @Headers({ + "Content-Type:{{mediaType}}" + }) + {{/-first}} + {{/prioritizedContentTypes}} + {{/formParams}} @{{httpMethod}}("{{path}}") {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java new file mode 100644 index 00000000000..2dceedacf93 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/languages/JavaClientCodegenTest.java @@ -0,0 +1,79 @@ +package io.swagger.codegen.languages; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class JavaClientCodegenTest { + + private static final String VENDOR_MIME_TYPE = "application/vnd.company.v1+json"; + private static final String XML_MIME_TYPE = "application/xml"; + private static final String JSON_MIME_TYPE = "application/json"; + private static final String TEXT_MIME_TYPE = "text/plain"; + + @Test + public void testJsonMime() { + Assert.assertTrue(JavaClientCodegen.isJsonMimeType(JSON_MIME_TYPE)); + Assert.assertFalse(JavaClientCodegen.isJsonMimeType(XML_MIME_TYPE)); + Assert.assertFalse(JavaClientCodegen.isJsonMimeType(TEXT_MIME_TYPE)); + + Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany+json")); + Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.v1+json")); + Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeA.version1+json")); + Assert.assertTrue(JavaClientCodegen.isJsonVendorMimeType("application/vnd.mycompany.resourceTypeB.version2+json")); + Assert.assertFalse(JavaClientCodegen.isJsonVendorMimeType("application/v.json")); + + } + + @Test + public void testContentTypePrioritization() { + Map jsonMimeType = new HashMap<>(); + jsonMimeType.put(JavaClientCodegen.MEDIA_TYPE, JSON_MIME_TYPE); + + Map xmlMimeType = new HashMap<>(); + xmlMimeType.put(JavaClientCodegen.MEDIA_TYPE, XML_MIME_TYPE); + + Map vendorMimeType = new HashMap<>(); + vendorMimeType.put(JavaClientCodegen.MEDIA_TYPE, VENDOR_MIME_TYPE); + + Map textMimeType = new HashMap<>(); + textMimeType.put(JavaClientCodegen.MEDIA_TYPE, TEXT_MIME_TYPE); + + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes( + Collections.>emptyList()), Collections.emptyList()); + + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType)), Arrays.asList(xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType)), Arrays.asList(jsonMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(vendorMimeType)), Arrays.asList(vendorMimeType)); + + + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, jsonMimeType)), + Arrays.asList(jsonMimeType, xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, xmlMimeType)), + Arrays.asList(jsonMimeType, xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(jsonMimeType, vendorMimeType)), + Arrays.asList(vendorMimeType, jsonMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(textMimeType, xmlMimeType)), + Arrays.asList(textMimeType, xmlMimeType)); + Assert.assertEquals(JavaClientCodegen.prioritizeContentTypes(Arrays.asList(xmlMimeType, textMimeType)), + Arrays.asList(xmlMimeType, textMimeType)); + + System.out.println(JavaClientCodegen.prioritizeContentTypes(Arrays.asList( + xmlMimeType,textMimeType, jsonMimeType, vendorMimeType))); + + List> priContentTypes = JavaClientCodegen.prioritizeContentTypes(Arrays.asList( + xmlMimeType, textMimeType, jsonMimeType, vendorMimeType)); + Assert.assertEquals(priContentTypes, Arrays.asList(vendorMimeType, jsonMimeType, xmlMimeType, textMimeType)); + + for ( int i = 0; i < 3; i++ ) + Assert.assertNotNull(priContentTypes.get(i).get("hasMore")); + Assert.assertNull(priContentTypes.get(3).get("hasMore")); + + } + +} diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-vendor-mime.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-vendor-mime.yaml new file mode 100644 index 00000000000..57380003800 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-vendor-mime.yaml @@ -0,0 +1,1232 @@ +swagger: '2.0' +info: + description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" + version: 1.0.0 + title: Swagger Petstore + termsOfService: 'http://swagger.io/terms/' + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: 'http://www.apache.org/licenses/LICENSE-2.0.html' +host: petstore.swagger.io +basePath: /v2 +tags: + - name: pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: 'http://swagger.io' + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user + externalDocs: + description: Find out more about our store + url: 'http://swagger.io' +schemes: + - http +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + consumes: + - application/vnd.mycompany.resA.v1+json + - application/xml + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + consumes: + - application/vnd.mycompany.v1+json + - application/xml + produces: + - application/json + parameters: + - in: body + name: body + description: Pet object that needs to be added to the store + required: true + schema: + $ref: '#/definitions/Pet' + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + produces: + - application/xml + - application/json + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: 'Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.' + operationId: findPetsByTags + produces: + - application/xml + - application/json + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + type: array + items: + type: string + collectionFormat: csv + responses: + '200': + description: successful operation + schema: + type: array + items: + $ref: '#/definitions/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + type: integer + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + consumes: + - application/x-www-form-urlencoded + produces: + - application/xml + - application/json + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + type: integer + format: int64 + - name: name + in: formData + description: Updated name of the pet + required: false + type: string + - name: status + in: formData + description: Updated status of the pet + required: false + type: string + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + produces: + - application/xml + - application/json + parameters: + - name: api_key + in: header + required: false + type: string + - name: petId + in: path + description: Pet id to delete + required: true + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + consumes: + - multipart/form-data + produces: + - application/json + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + type: integer + format: int64 + - name: additionalMetadata + in: formData + description: Additional data to pass to server + required: false + type: string + - name: file + in: formData + description: file to upload + required: false + type: file + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + produces: + - application/json + parameters: [] + responses: + '200': + description: successful operation + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: order placed for purchasing the pet + required: true + schema: + $ref: '#/definitions/Order' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid Order + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: 'For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions' + operationId: getOrderById + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + type: integer + maximum: 5 + minimum: 1 + format: int64 + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + operationId: deleteOrder + produces: + - application/xml + - application/json + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + type: string + minimum: 1 + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: Created user object + required: true + schema: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + produces: + - application/xml + - application/json + parameters: + - in: body + name: body + description: List of user object + required: true + schema: + type: array + items: + $ref: '#/definitions/User' + responses: + default: + description: successful operation + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: query + description: The user name for login + required: true + type: string + - name: password + in: query + description: The password for login in clear text + required: true + type: string + responses: + '200': + description: successful operation + schema: + type: string + headers: + X-Rate-Limit: + type: integer + format: int32 + description: calls per hour allowed by the user + X-Expires-After: + type: string + format: date-time + description: date in UTC when toekn expires + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + produces: + - application/xml + - application/json + parameters: [] + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + type: string + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + type: string + - in: body + name: body + description: Updated user object + required: true + schema: + $ref: '#/definitions/User' + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + produces: + - application/xml + - application/json + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + + /fake: + patch: + tags: + - fake + summary: To test "client" model + descriptions: To test "client" model + operationId: testClientModel + consumes: + - application/json + produces: + - application/json + parameters: + - in: body + name: body + description: client model + required: true + schema: + $ref: '#/definitions/Client' + responses: + '200': + description: successful operation + schema: + $ref: '#/definitions/Client' + get: + tags: + - fake + summary: To test enum parameters + descriptions: To test enum parameters + operationId: testEnumParameters + consumes: + - application/json + produces: + - application/json + parameters: + - name: enum_form_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: formData + description: Form parameter enum test (string array) + - name: enum_form_string + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + in: formData + description: Form parameter enum test (string) + - name: enum_header_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: header + description: Header parameter enum test (string array) + - name: enum_header_string + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + in: header + description: Header parameter enum test (string) + - name: enum_query_string_array + type: array + items: + type: string + default: '$' + enum: + - '>' + - '$' + in: query + description: Query parameter enum test (string array) + - name: enum_query_string + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + in: query + description: Query parameter enum test (string) + - name: enum_query_integer + type: number + format: int32 + enum: + - 1 + - -2 + in: query + description: Query parameter enum test (double) + - name: enum_query_double + type: number + format: double + enum: + - 1.1 + - -1.2 + in: formData + description: Query parameter enum test (double) + responses: + '400': + description: Invalid request + '404': + description: Not found + post: + tags: + - fake + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + consumes: + - application/xml; charset=utf-8 + - application/json; charset=utf-8 + produces: + - application/xml; charset=utf-8 + - application/json; charset=utf-8 + parameters: + - name: integer + type: integer + maximum: 100 + minimum: 10 + in: formData + description: None + - name: int32 + type: integer + format: int32 + maximum: 200 + minimum: 20 + in: formData + description: None + - name: int64 + type: integer + format: int64 + in: formData + description: None + - name: number + type: number + maximum: 543.2 + minimum: 32.1 + in: formData + description: None + required: true + - name: float + type: number + format: float + maximum: 987.6 + in: formData + description: None + - name: double + type: number + in: formData + format: double + maximum: 123.4 + minimum: 67.8 + required: true + description: None + - name: string + type: string + pattern: /[a-z]/i + in: formData + description: None + - name: pattern_without_delimiter + type: string + pattern: "^[A-Z].*" + in: formData + description: None + required: true + - name: byte + type: string + format: byte + in: formData + description: None + required: true + - name: binary + type: string + format: binary + in: formData + description: None + - name: date + type: string + format: date + in: formData + description: None + - name: dateTime + type: string + format: date-time + in: formData + description: None + - name: password + type: string + format: password + maxLength: 64 + minLength: 10 + in: formData + description: None + - name: callback + type: string + in: formData + description: None + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - http_basic_test: [] +securityDefinitions: + petstore_auth: + type: oauth2 + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + flow: implicit + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + http_basic_test: + type: basic +definitions: + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-is-unique: true + category: + $ref: '#/definitions/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/definitions/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + '$special[model.name]': + properties: + '$special[property.name]': + type: integer + format: int64 + xml: + name: '$special[model.name]' + Return: + description: Model for testing reserved words + properties: + return: + type: integer + format: int32 + xml: + name: Return + Name: + description: Model for testing model name same as property name + required: + - name + properties: + name: + type: integer + format: int32 + snake_case: + readOnly: true + type: integer + format: int32 + property: + type: string + 123Number: + type: integer + readOnly: true + xml: + name: Name + 200_response: + description: Model for testing model name starting with number + properties: + name: + type: integer + format: int32 + class: + type: string + xml: + name: Name + Dog: + allOf: + - $ref: '#/definitions/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/definitions/Animal' + - type: object + properties: + declawed: + type: boolean + Animal: + type: object + discriminator: className + required: + - className + properties: + className: + type: string + color: + type: string + default: 'red' + AnimalFarm: + type: array + items: + $ref: '#/definitions/Animal' + format_test: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + int32: + type: integer + format: int32 + maximum: 200 + minimum: 20 + int64: + type: integer + format: int64 + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + type: number + format: float + maximum: 987.6 + minimum: 54.3 + double: + type: number + format: double + maximum: 123.4 + minimum: 67.8 + string: + type: string + pattern: /[a-z]/i + byte: + type: string + format: byte + binary: + type: string + format: binary + date: + type: string + format: date + dateTime: + type: string + format: date-time + uuid: + type: string + format: uuid + password: + type: string + format: password + maxLength: 64 + minLength: 10 + EnumClass: + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + Enum_Test: + type: object + properties: + enum_string: + type: string + enum: + - UPPER + - lower + enum_integer: + type: integer + format: int32 + enum: + - 1 + - -1 + enum_number: + type: number + format: double + enum: + - 1.1 + - -1.2 + AdditionalPropertiesClass: + type: object + properties: + map_property: + type: object + additionalProperties: + type: string + map_of_map_property: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + MixedPropertiesAndAdditionalPropertiesClass: + type: object + properties: + uuid: + type: string + format: uuid + dateTime: + type: string + format: date-time + map: + type: object + additionalProperties: + $ref: '#/definitions/Animal' + List: + type: object + properties: + 123-list: + type: string + Client: + type: object + properties: + client: + type: string + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + hasOnlyReadOnly: + type: object + properties: + bar: + type: string + readOnly: true + foo: + type: string + readOnly: true + MapTest: + type: object + properties: + map_map_of_string: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + # comment out the following (map of map of enum) as many language not yet support this + #map_map_of_enum: + # type: object + # additionalProperties: + # type: object + # additionalProperties: + # type: string + # enum: + # - UPPER + # - lower + map_of_enum_string: + type: object + additionalProperties: + type: string + enum: + - UPPER + - lower + ArrayTest: + type: object + properties: + array_of_string: + type: array + items: + type: string + array_array_of_integer: + type: array + items: + type: array + items: + type: integer + format: int64 + array_array_of_model: + type: array + items: + type: array + items: + $ref: '#/definitions/ReadOnlyFirst' + # commented out the below test case for array of enum for the time being + # as not all language can handle it + #array_of_enum: + # type: array + # items: + # type: string + # enum: + # - UPPER + # - lower + NumberOnly: + type: object + properties: + JustNumber: + type: number + ArrayOfNumberOnly: + type: object + properties: + ArrayNumber: + type: array + items: + type: number + ArrayOfArrayOfNumberOnly: + type: object + properties: + ArrayArrayNumber: + type: array + items: + type: array + items: + type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - ">=" + - "$" + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + # comment out the following as 2d array of enum is not supported at the moment + #array_array_enum: + # type: array + # items: + # type: array + # items: + # type: string + # enum: + # - Cat + # - Dog +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index d1068513f0e..ba826f92d08 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -10,8 +10,8 @@ import okhttp3.RequestBody; import io.swagger.client.model.Client; import org.joda.time.LocalDate; -import org.joda.time.DateTime; import java.math.BigDecimal; +import org.joda.time.DateTime; import java.util.ArrayList; import java.util.HashMap; @@ -26,6 +26,9 @@ public interface FakeApi { * @return Call<Client> */ + @Headers({ + "Content-Type:application/json" + }) @PATCH("fake") Call testClientModel( @retrofit2.http.Body Client body 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 index 3f61279a66b..64ebfe75750 100644 --- 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 @@ -9,8 +9,8 @@ import retrofit2.http.*; import okhttp3.RequestBody; import io.swagger.client.model.Pet; -import java.io.File; import io.swagger.client.model.ModelApiResponse; +import java.io.File; import java.util.ArrayList; import java.util.HashMap; @@ -25,6 +25,9 @@ public interface PetApi { * @return Call<Void> */ + @Headers({ + "Content-Type:application/json" + }) @POST("pet") Call addPet( @retrofit2.http.Body Pet body @@ -86,6 +89,9 @@ public interface PetApi { * @return Call<Void> */ + @Headers({ + "Content-Type:application/json" + }) @PUT("pet") Call updatePet( @retrofit2.http.Body Pet body From 1e975637c9d67ef96364b5a1d1ba6f176d6116c1 Mon Sep 17 00:00:00 2001 From: walthema Date: Mon, 24 Oct 2016 15:04:55 +0200 Subject: [PATCH 005/269] Fixed enum marshalling & fromValue() Added toString() to enums --- .../resources/JavaJaxRS/cxf/enumClass.mustache | 16 +++++++++++++--- .../main/resources/JavaJaxRS/cxf/pojo.mustache | 1 + .../gen/java/io/swagger/model/Category.java | 1 + .../java/io/swagger/model/ModelApiResponse.java | 1 + .../gen/java/io/swagger/model/Order.java | 17 ++++++++++++++--- .../gen/java/io/swagger/model/Pet.java | 17 ++++++++++++++--- .../gen/java/io/swagger/model/Tag.java | 1 + .../gen/java/io/swagger/model/User.java | 1 + 8 files changed, 46 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache index 94212231156..10bb9d0f4e0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache @@ -1,9 +1,9 @@ @XmlType(name="{{datatypeWithEnum}}") -@XmlEnum +@XmlEnum({{datatype}}.class) public enum {{datatypeWithEnum}} { {{#allowableValues}} - {{#enumVars}}{{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{#enumVars}}@XmlEnumValue({{{value}}}) {{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/allowableValues}} @@ -17,7 +17,17 @@ public enum {{datatypeWithEnum}} { return value; } + @Override + public String toString() { + return String.valueOf(value); + } + public static {{datatypeWithEnum}} fromValue(String v) { - return valueOf(v); + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index c214ae2ae84..3734c525a2b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -4,6 +4,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) {{#hasVars}} @XmlType(name = "{{classname}}", propOrder = diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java index c84e936b3b4..ecd7630f6a7 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Category", propOrder = diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java index 950307540f4..dc8a57cf13a 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ModelApiResponse", propOrder = diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java index d3d9ffabfb5..ec2140e1b4d 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Order", propOrder = @@ -31,10 +32,10 @@ public class Order { private javax.xml.datatype.XMLGregorianCalendar shipDate = null; @XmlType(name="StatusEnum") -@XmlEnum +@XmlEnum(String.class) public enum StatusEnum { - PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); private String value; @@ -47,8 +48,18 @@ public enum StatusEnum { return value; } + @Override + public String toString() { + return String.valueOf(value); + } + public static StatusEnum fromValue(String v) { - return valueOf(v); + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; } } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java index 3c1adb7d97f..5a636e92c33 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java @@ -12,6 +12,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Pet", propOrder = @@ -38,10 +39,10 @@ public class Pet { private List tags = new ArrayList(); @XmlType(name="StatusEnum") -@XmlEnum +@XmlEnum(String.class) public enum StatusEnum { - AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); private String value; @@ -54,8 +55,18 @@ public enum StatusEnum { return value; } + @Override + public String toString() { + return String.valueOf(value); + } + public static StatusEnum fromValue(String v) { - return valueOf(v); + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; } } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java index 1eddc2f761f..848da3841f0 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Tag", propOrder = diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java index f66d1df57e0..e08637a5777 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "User", propOrder = From 40ec83a0918f1123508d1e64d4ac2f4c22cfe207 Mon Sep 17 00:00:00 2001 From: AndrewRademacher Date: Mon, 24 Oct 2016 16:12:10 -0500 Subject: [PATCH 006/269] Fixed toUpper and toLower usage in haskell-servant gen. --- .../languages/HaskellServantCodegen.java | 24 +++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index da6642ddef9..526ce0b10b2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -158,6 +158,26 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf return name + "_"; } + public String firstLetterToUpper(String word) { + if (word.length() == 0) { + return word; + } else if (word.length() == 1) { + return word.substring(0, 1).toUpperCase(); + } else { + return word.substring(0, 1).toUpperCase() + word.substring(1); + } + } + + public String firstLetterToLower(String word) { + if (word.length() == 0) { + return word; + } else if (word.length() == 1) { + return word.substring(0, 1).toLowerCase(); + } else { + return word.substring(0, 1).toLowerCase() + word.substring(1); + } + } + @Override public void preprocessSwagger(Swagger swagger) { // From the title, compute a reasonable name for the package and the API @@ -185,7 +205,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf // The API name is made by appending the capitalized words of the title List wordsCaps = new ArrayList(); for (String word : words) { - wordsCaps.add(word.substring(0, 1).toUpperCase() + word.substring(1)); + wordsCaps.add(firstLetterToUpper(word)); } String apiName = joinStrings("", wordsCaps); @@ -196,7 +216,7 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf additionalProperties.put("title", apiName); - additionalProperties.put("titleLower", apiName.substring(0, 1).toLowerCase() + apiName.substring(1)); + additionalProperties.put("titleLower", firstLetterToLower(apiName)); additionalProperties.put("package", cabalName); // Due to the way servant resolves types, we need a high context stack limit From 21ec2bc8664e77dbbeb2ccf01cc7c9c4eae20bc4 Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 25 Oct 2016 15:40:51 +0200 Subject: [PATCH 007/269] [spring] add an option to choose the response wrapper type Also generate the spring-cloud sample with a HystrixCommand wrapper --- bin/spring-cloud-feign-petstore.sh | 2 +- .../codegen/languages/SpringCodegen.java | 41 +++++++++ .../main/resources/JavaSpring/api.mustache | 2 +- .../libraries/spring-cloud/pom.mustache | 4 +- .../options/SpringOptionsProvider.java | 2 + .../codegen/spring/SpringOptionsTest.java | 2 + samples/client/petstore/spring-cloud/pom.xml | 4 +- .../src/main/java/io/swagger/api/PetApi.java | 16 ++-- .../main/java/io/swagger/api/StoreApi.java | 8 +- .../src/main/java/io/swagger/api/UserApi.java | 16 ++-- .../src/test/java/io/swagger/Application.java | 20 +++++ .../test/java/io/swagger/api/PetApiTest.java | 85 ++++++++----------- .../java/io/swagger/api/StoreApiTest.java | 39 ++++----- .../test/java/io/swagger/api/UserApiTest.java | 37 +++----- .../src/test/resources/application.yml | 8 +- 15 files changed, 157 insertions(+), 129 deletions(-) create mode 100644 samples/client/petstore/spring-cloud/src/test/java/io/swagger/Application.java diff --git a/bin/spring-cloud-feign-petstore.sh b/bin/spring-cloud-feign-petstore.sh index a5605217b07..9f76a40ded5 100755 --- a/bin/spring-cloud-feign-petstore.sh +++ b/bin/spring-cloud-feign-petstore.sh @@ -26,7 +26,7 @@ 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 -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l spring -c bin/spring-cloud-feign-petstore.json -o samples/client/petstore/spring-cloud -DhideGenerationTimestamp=true,responseWrapper=HystrixCommand" echo "Removing files and folders under samples/client/petstore/spring-cloud/src/main" rm -rf samples/client/petstore/spring-cloud/src/main diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 43c0a90e4c2..2b0cb059f21 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -17,6 +17,7 @@ public class SpringCodegen extends AbstractJavaCodegen { public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String JAVA_8 = "java8"; public static final String ASYNC = "async"; + public static final String RESPONSE_WRAPPER = "responseWrapper"; public static final String SPRING_MVC_LIBRARY = "spring-mvc"; public static final String SPRING_CLOUD_LIBRARY = "spring-cloud"; @@ -27,6 +28,7 @@ public class SpringCodegen extends AbstractJavaCodegen { protected boolean singleContentTypes = false; protected boolean java8 = false; protected boolean async = false; + protected String responseWrapper = ""; public SpringCodegen() { super(); @@ -51,6 +53,7 @@ public class SpringCodegen extends AbstractJavaCodegen { cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); + cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); @@ -117,6 +120,10 @@ public class SpringCodegen extends AbstractJavaCodegen { this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString())); } + if (additionalProperties.containsKey(RESPONSE_WRAPPER)) { + this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER)); + } + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -173,11 +180,43 @@ public class SpringCodegen extends AbstractJavaCodegen { if (this.java8) { additionalProperties.put("javaVersion", "1.8"); additionalProperties.put("jdk8", "true"); + if (this.async) { + additionalProperties.put(RESPONSE_WRAPPER, "CompletableFuture"); + } typeMapping.put("date", "LocalDate"); typeMapping.put("DateTime", "OffsetDateTime"); importMapping.put("LocalDate", "java.time.LocalDate"); importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + } else if (this.async) { + additionalProperties.put(RESPONSE_WRAPPER, "Callable"); } + + // Some well-known Spring or Spring-Cloud response wrappers + switch (this.responseWrapper) { + case "Future": + case "Callable": + case "CompletableFuture": + additionalProperties.put(RESPONSE_WRAPPER, "java.util.concurrent" + this.responseWrapper); + break; + case "ListenableFuture": + additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.util.concurrent.ListenableFuture"); + break; + case "DeferredResult": + additionalProperties.put(RESPONSE_WRAPPER, "org.springframework.web.context.request.DeferredResult"); + break; + case "HystrixCommand": + additionalProperties.put(RESPONSE_WRAPPER, "com.netflix.hystrix.HystrixCommand"); + break; + case "RxObservable": + additionalProperties.put(RESPONSE_WRAPPER, "rx.Observable"); + break; + case "RxSingle": + additionalProperties.put(RESPONSE_WRAPPER, "rx.Single"); + break; + default: + break; + } + } @Override @@ -355,6 +394,8 @@ public class SpringCodegen extends AbstractJavaCodegen { public void setAsync(boolean async) { this.async = async; } + public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache index 8852a36b9b9..4a97c5d5f33 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache @@ -43,7 +43,7 @@ public interface {{classname}} { produces = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}}{{#hasConsumes}} consumes = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}}{{/singleContentTypes}} method = RequestMethod.{{httpMethod}}) - {{#jdk8}}default {{/jdk8}}{{#async}}{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture<{{/jdk8}}{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} { // do some magic! return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache index 84e0b0c2f99..f8f7d16f02b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.6.RELEASE + 1.4.1.RELEASE src/main/java @@ -25,7 +25,7 @@ org.springframework.cloud spring-cloud-starter-parent - Brixton.SR2 + Camden.SR1 pom import diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index 3cc8bfee148..de7caa0d6c7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -15,6 +15,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { public static final String SINGLE_CONTENT_TYPES = "true"; public static final String JAVA_8 = "true"; public static final String ASYNC = "true"; + public static final String RESPONSE_WRAPPER = "Callable"; @Override public String getLanguage() { @@ -32,6 +33,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); options.put(SpringCodegen.JAVA_8, JAVA_8); options.put(SpringCodegen.ASYNC, ASYNC); + options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER); return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 8adaa67679d..4084c0a80e9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -64,6 +64,8 @@ public class SpringOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); times = 1; + clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); + times = 1; }}; } diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml index 159fdae3e61..38b81bfaae5 100644 --- a/samples/client/petstore/spring-cloud/pom.xml +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.3.6.RELEASE + 1.4.1.RELEASE src/main/java @@ -25,7 +25,7 @@ org.springframework.cloud spring-cloud-starter-parent - Brixton.SR2 + Camden.SR1 pom import diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 4bba62c661d..812ca04e270 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -33,7 +33,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + com.netflix.hystrix.HystrixCommand> addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { @@ -48,7 +48,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + com.netflix.hystrix.HystrixCommand> deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); @@ -65,7 +65,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + com.netflix.hystrix.HystrixCommand>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -81,7 +81,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + com.netflix.hystrix.HystrixCommand>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @@ -95,7 +95,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + com.netflix.hystrix.HystrixCommand> getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { @@ -112,7 +112,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.PUT) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + com.netflix.hystrix.HystrixCommand> updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { @@ -127,7 +127,7 @@ public interface PetApi { produces = "application/json", consumes = "application/x-www-form-urlencoded", method = RequestMethod.POST) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + com.netflix.hystrix.HystrixCommand> updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, @ApiParam(value = "Updated name of the pet" ) @RequestParam(value="name", required=false) String name, @ApiParam(value = "Updated status of the pet" ) @RequestParam(value="status", required=false) String status); @@ -144,7 +144,7 @@ public interface PetApi { produces = "application/json", consumes = "multipart/form-data", method = RequestMethod.POST) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + com.netflix.hystrix.HystrixCommand> uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, @ApiParam(value = "Additional data to pass to server" ) @RequestParam(value="additionalMetadata", required=false) String additionalMetadata, @ApiParam(value = "file detail") @RequestParam("file") MultipartFile file); diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java index 1eb724e96c9..4442f2ff784 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java @@ -28,7 +28,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + com.netflix.hystrix.HystrixCommand> deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @@ -40,7 +40,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> getInventory(); + com.netflix.hystrix.HystrixCommand>> getInventory(); @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @@ -52,7 +52,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + com.netflix.hystrix.HystrixCommand> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @@ -63,6 +63,6 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + com.netflix.hystrix.HystrixCommand> placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); } diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java index 40bdddedbb8..2cfdd979685 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -27,7 +27,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + com.netflix.hystrix.HystrixCommand> createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @@ -37,7 +37,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + com.netflix.hystrix.HystrixCommand> createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @@ -47,7 +47,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.POST) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + com.netflix.hystrix.HystrixCommand> createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @@ -58,7 +58,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.DELETE) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + com.netflix.hystrix.HystrixCommand> deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @@ -70,7 +70,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + com.netflix.hystrix.HystrixCommand> getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @@ -81,7 +81,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + com.netflix.hystrix.HystrixCommand> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @@ -92,7 +92,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity logoutUser(); + com.netflix.hystrix.HystrixCommand> logoutUser(); @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @@ -103,7 +103,7 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.PUT) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + com.netflix.hystrix.HystrixCommand> updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); } diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/Application.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/Application.java new file mode 100644 index 00000000000..372b8da31e7 --- /dev/null +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/Application.java @@ -0,0 +1,20 @@ +package io.swagger; + +import feign.Logger; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.context.annotation.Bean; + +@SpringBootApplication +@EnableFeignClients +public class Application { + public static void main(String[] args) { + new SpringApplicationBuilder(Application.class).run(args); + } + + @Bean + Logger.Level feignLoggerLevel() { + return Logger.Level.FULL; + } +} diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java index a08dccc2a60..f369ac786ca 100644 --- a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/PetApiTest.java @@ -1,30 +1,28 @@ package io.swagger.api; -import feign.FeignException; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import io.swagger.Application; import io.swagger.TestUtils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - import io.swagger.model.Category; import io.swagger.model.Pet; import io.swagger.model.Tag; -import org.junit.*; +import org.junit.Ignore; +import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.cloud.netflix.feign.EnableFeignClients; -import org.springframework.http.ResponseEntity; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = PetApiTest.Application.class) +@SpringBootTest(classes = Application.class) public class PetApiTest { @Autowired @@ -33,9 +31,8 @@ public class PetApiTest { @Test public void testCreateAndGetPet() { Pet pet = createRandomPet(); - client.addPet(pet); - ResponseEntity rp = client.getPetById(pet.getId()); - Pet fetched = rp.getBody(); + client.addPet(pet).execute(); + Pet fetched = client.getPetById(pet.getId()).execute().getBody(); assertNotNull(fetched); assertEquals(pet.getId(), fetched.getId()); assertNotNull(fetched.getCategory()); @@ -47,9 +44,9 @@ public class PetApiTest { Pet pet = createRandomPet(); pet.setName("programmer"); - client.updatePet(pet); + client.updatePet(pet).execute(); - Pet fetched = client.getPetById(pet.getId()).getBody(); + Pet fetched = client.getPetById(pet.getId()).execute().getBody(); assertNotNull(fetched); assertEquals(pet.getId(), fetched.getId()); assertNotNull(fetched.getCategory()); @@ -63,9 +60,9 @@ public class PetApiTest { pet.setName("programmer"); pet.setStatus(Pet.StatusEnum.AVAILABLE); - client.updatePet(pet); + client.updatePet(pet).execute(); - List pets = client.findPetsByStatus(Arrays.asList(new String[]{"available"})).getBody(); + List pets = client.findPetsByStatus(Collections.singletonList("available")).execute().getBody(); assertNotNull(pets); boolean found = false; @@ -92,9 +89,9 @@ public class PetApiTest { tags.add(tag1); pet.setTags(tags); - client.updatePet(pet); + client.updatePet(pet).execute(); - List pets = client.findPetsByTags(Arrays.asList(new String[]{"friendly"})).getBody(); + List pets = client.findPetsByTags(Collections.singletonList("friendly")).execute().getBody(); assertNotNull(pets); boolean found = false; @@ -111,12 +108,12 @@ public class PetApiTest { public void testUpdatePetWithForm() throws Exception { Pet pet = createRandomPet(); pet.setName("frank"); - client.addPet(pet); + client.addPet(pet).execute(); - Pet fetched = client.getPetById(pet.getId()).getBody(); + Pet fetched = client.getPetById(pet.getId()).execute().getBody(); - client.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = client.getPetById(fetched.getId()).getBody(); + client.updatePetWithForm(fetched.getId(), "furt", null).execute(); + Pet updated = client.getPetById(fetched.getId()).execute().getBody(); assertEquals(updated.getName(), "furt"); } @@ -124,16 +121,16 @@ public class PetApiTest { @Test public void testDeletePet() throws Exception { Pet pet = createRandomPet(); - client.addPet(pet); + client.addPet(pet).execute(); - Pet fetched = client.getPetById(pet.getId()).getBody(); - client.deletePet(fetched.getId(), null); + Pet fetched = client.getPetById(pet.getId()).execute().getBody(); + client.deletePet(fetched.getId(), null).execute(); try { - client.getPetById(fetched.getId()); + client.getPetById(fetched.getId()).execute(); fail("expected an error"); - } catch (FeignException e) { - assertTrue(e.getMessage().startsWith("status 404 ")); + } catch (HystrixRuntimeException e) { + assertTrue(e.getCause().getMessage().startsWith("status 404 ")); } } @@ -141,10 +138,10 @@ public class PetApiTest { @Test public void testUploadFile() throws Exception { Pet pet = createRandomPet(); - client.addPet(pet); + client.addPet(pet).execute(); MockMultipartFile filePart = new MockMultipartFile("file", "bar".getBytes()); - client.uploadFile(pet.getId(), "a test file", filePart); + client.uploadFile(pet.getId(), "a test file", filePart).execute(); } @Test @@ -158,7 +155,7 @@ public class PetApiTest { assertTrue(pet1.hashCode() == pet1.hashCode()); pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + pet2.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); assertFalse(pet1.equals(pet2)); assertFalse(pet2.equals(pet1)); assertFalse(pet1.hashCode() == (pet2.hashCode())); @@ -166,7 +163,7 @@ public class PetApiTest { assertTrue(pet2.hashCode() == pet2.hashCode()); pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"})); + pet1.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); assertTrue(pet1.equals(pet2)); assertTrue(pet2.equals(pet1)); assertTrue(pet1.hashCode() == pet2.hashCode()); @@ -184,24 +181,10 @@ public class PetApiTest { pet.setCategory(category); pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + List photos = Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"); pet.setPhotoUrls(photos); return pet; } - - @SpringBootApplication - @EnableFeignClients - protected static class Application { - public static void main(String[] args) { - new SpringApplicationBuilder(Application.class).run(args); - } - } - - - - - - } diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java index 223289baf15..a5538aaeacd 100644 --- a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/StoreApiTest.java @@ -1,15 +1,13 @@ package io.swagger.api; -import feign.FeignException; +import com.netflix.hystrix.exception.HystrixRuntimeException; +import io.swagger.Application; import io.swagger.TestUtils; import io.swagger.model.Order; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.lang.reflect.Field; @@ -18,7 +16,7 @@ import java.util.Map; import static org.junit.Assert.*; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = StoreApiTest.Application.class) +@SpringBootTest(classes = Application.class) public class StoreApiTest { @Autowired @@ -26,16 +24,16 @@ public class StoreApiTest { @Test public void testGetInventory() { - Map inventory = client.getInventory().getBody(); + Map inventory = client.getInventory().execute().getBody(); assertTrue(inventory.keySet().size() > 0); } @Test public void testPlaceOrder() { Order order = createOrder(); - client.placeOrder(order); + client.placeOrder(order).execute(); - Order fetched = client.getOrderById(order.getId()).getBody(); + Order fetched = client.getOrderById(order.getId()).execute().getBody(); assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); @@ -45,25 +43,25 @@ public class StoreApiTest { @Test public void testDeleteOrder() { Order order = createOrder(); - client.placeOrder(order); + client.placeOrder(order).execute(); - Order fetched = client.getOrderById(order.getId()).getBody(); + Order fetched = client.getOrderById(order.getId()).execute().getBody(); assertEquals(fetched.getId(), order.getId()); - client.deleteOrder(String.valueOf(order.getId())); + client.deleteOrder(String.valueOf(order.getId())).execute(); try { - client.getOrderById(order.getId()); + client.getOrderById(order.getId()).execute(); fail("expected an error"); - } catch (FeignException e) { - assertTrue(e.getMessage().startsWith("status 404 ")); + } catch (HystrixRuntimeException e) { + assertTrue(e.getCause().getMessage().startsWith("status 404 ")); } } private Order createOrder() { Order order = new Order(); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); + order.setPetId(200L); + order.setQuantity(13); order.setShipDate(org.joda.time.DateTime.now()); order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); @@ -79,11 +77,4 @@ public class StoreApiTest { return order; } - @SpringBootApplication - @EnableFeignClients - protected static class Application { - public static void main(String[] args) { - new SpringApplicationBuilder(StoreApiTest.Application.class).run(args); - } - } } diff --git a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java index 4fb9b5e1a12..b0ffb72e7b5 100644 --- a/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java +++ b/samples/client/petstore/spring-cloud/src/test/java/io/swagger/api/UserApiTest.java @@ -1,23 +1,21 @@ package io.swagger.api; +import io.swagger.Application; import io.swagger.TestUtils; import io.swagger.model.User; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.boot.test.SpringApplicationConfiguration; -import org.springframework.cloud.netflix.feign.EnableFeignClients; +import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Arrays; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) -@SpringApplicationConfiguration(classes = UserApiTest.Application.class) - +@SpringBootTest(classes = Application.class) public class UserApiTest { @Autowired @@ -27,9 +25,9 @@ public class UserApiTest { public void testCreateUser() { User user = createUser(); - client.createUser(user); + client.createUser(user).execute(); - User fetched = client.getUserByName(user.getUsername()).getBody(); + User fetched = client.getUserByName(user.getUsername()).execute().getBody(); assertEquals(user.getId(), fetched.getId()); } @@ -40,9 +38,9 @@ public class UserApiTest { User user2 = createUser(); user2.setUsername("user" + user2.getId()); - client.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + client.createUsersWithArrayInput(Arrays.asList(user1, user2)).execute(); - User fetched = client.getUserByName(user1.getUsername()).getBody(); + User fetched = client.getUserByName(user1.getUsername()).execute().getBody(); assertEquals(user1.getId(), fetched.getId()); } @@ -53,24 +51,24 @@ public class UserApiTest { User user2 = createUser(); user2.setUsername("user" + user2.getId()); - client.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + client.createUsersWithListInput(Arrays.asList(user1, user2)).execute(); - User fetched = client.getUserByName(user1.getUsername()).getBody(); + User fetched = client.getUserByName(user1.getUsername()).execute().getBody(); assertEquals(user1.getId(), fetched.getId()); } @Test public void testLoginUser() { User user = createUser(); - client.createUser(user); + client.createUser(user).execute(); - String token = client.loginUser(user.getUsername(), user.getPassword()).getBody(); + String token = client.loginUser(user.getUsername(), user.getPassword()).execute().getBody(); assertTrue(token.startsWith("logged in user session:")); } @Test public void logoutUser() { - client.logoutUser(); + client.logoutUser().execute(); } private User createUser() { @@ -87,11 +85,4 @@ public class UserApiTest { return user; } - @SpringBootApplication - @EnableFeignClients - protected static class Application { - public static void main(String[] args) { - new SpringApplicationBuilder(UserApiTest.Application.class).run(args); - } - } } diff --git a/samples/client/petstore/spring-cloud/src/test/resources/application.yml b/samples/client/petstore/spring-cloud/src/test/resources/application.yml index 07a52419295..8526829f0eb 100644 --- a/samples/client/petstore/spring-cloud/src/test/resources/application.yml +++ b/samples/client/petstore/spring-cloud/src/test/resources/application.yml @@ -2,9 +2,7 @@ spring: application: name: petstore-test -feign.hystrix.enabled: false +hystrix.command.default.execution.timeout.enabled: false + +logging.level.io.swagger.api: DEBUG -logging.level.io.swagger.api: - PetApiClient: DEBUG - StoreApiClient: DEBUG - UserApiClient: DEBUG From f57e7c0933eb371c643b5ddf8b350406c548b514 Mon Sep 17 00:00:00 2001 From: schnabel Date: Tue, 25 Oct 2016 20:09:24 +0200 Subject: [PATCH 008/269] bugfix: issue-4051 --- .../languages/AbstractJavaCodegen.java | 16 +++++++++--- .../swagger/codegen/java/JavaModelTest.java | 26 +++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 9bd2484b474..4e1ddab6d0a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -363,6 +363,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return name; } + if(startsWithTwoUppercaseLetters(name)){ + name = name.substring(0, 2).toLowerCase() + name.substring(2); + } + // camelize (lower first character) the variable name // pet_id => petId name = camelize(name, true); @@ -375,6 +379,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return name; } + private boolean startsWithTwoUppercaseLetters(String name) { + boolean startsWithTwoUppercaseLetters = false; + if(name.length() > 1) { + startsWithTwoUppercaseLetters = name.substring(0, 2).equals(name.substring(0, 2).toUpperCase()); + } + return startsWithTwoUppercaseLetters; + } + @Override public String toParamName(String name) { // to avoid conflicts with 'callback' parameter for async call @@ -935,8 +947,4 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return sb.toString(); } - public String toRegularExpression(String pattern) { - return escapeText(pattern); - } - } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 12784d6e92c..2805d4d63c2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -360,6 +360,32 @@ public class JavaModelTest { Assert.assertTrue(property.isNotContainer); } + @Test(description = "convert a model starting with two upper-case letter property names") + public void firstTwoUpperCaseLetterNamesTest() { + final Model model = new ModelImpl() + .description("a model with a property name starting with two upper-case letters") + .property("ATTName", new StringProperty()) + .required("ATTName"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "ATTName"); + Assert.assertEquals(property.getter, "getAtTName"); + Assert.assertEquals(property.setter, "setAtTName"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "atTName"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.required); + Assert.assertTrue(property.isNotContainer); + } + @Test(description = "convert hyphens per issue 503") public void hyphensTest() { final Model model = new ModelImpl() From 32edf04b8ec3a65f9c6e06446ea9726fefa1ae6b Mon Sep 17 00:00:00 2001 From: schnabel Date: Tue, 25 Oct 2016 20:37:55 +0200 Subject: [PATCH 009/269] fixed unwanted remove --- .../io/swagger/codegen/languages/AbstractJavaCodegen.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 4e1ddab6d0a..8c56e158d43 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -946,5 +946,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } return sb.toString(); } + + public String toRegularExpression(String pattern) { + return escapeText(pattern); + } } From 92af2cf8211a61291547eee137fdddaf862495e1 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 27 Oct 2016 12:59:51 -0700 Subject: [PATCH 010/269] updated versions --- pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pom.xml b/pom.xml index 5fbe4c8ae74..b22e0226fe8 100644 --- a/pom.xml +++ b/pom.xml @@ -780,10 +780,10 @@ - 1.0.22 + 1.0.23-SNAPSHOT 2.11.1 2.3.4 - 1.5.9 + 1.5.10 2.4 1.2 4.8.1 From 2651e83c0b8d5f01e8d0444fb5398a359ab524a0 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 27 Oct 2016 12:59:57 -0700 Subject: [PATCH 011/269] added trim --- .../io/swagger/codegen/config/CodegenConfiguratorUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java index a7592827879..b5a6a6355be 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java @@ -33,7 +33,7 @@ public final class CodegenConfiguratorUtils { public static void applyImportMappingsKvp(String importMappings, CodegenConfigurator configurator) { final Map map = createMapFromKeyValuePairs(importMappings); for (Map.Entry entry : map.entrySet()) { - configurator.addImportMapping(entry.getKey(), entry.getValue()); + configurator.addImportMapping(entry.getKey().trim(), entry.getValue().trim()); } } From 950a3eb2e8768075588c12d5c4c518eb7a270715 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 31 Oct 2016 19:14:32 -0700 Subject: [PATCH 012/269] Update pom.xml --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b22e0226fe8..aa94f36983e 100644 --- a/pom.xml +++ b/pom.xml @@ -780,7 +780,7 @@ - 1.0.23-SNAPSHOT + 1.0.23 2.11.1 2.3.4 1.5.10 From 7e7ca01aa411ec41301958bf1a7232fe56b6f927 Mon Sep 17 00:00:00 2001 From: Denis Bazhenov Date: Tue, 1 Nov 2016 18:21:30 +1000 Subject: [PATCH 013/269] Newline escaping disabled for HTML and HTML2 generators (#4099) * Newline escaping disabled Newline escaping disabled for HTML and HTML2 generators. Escaping failing Markdown processors to work correctly on descriptions * HTML examples updated --- .../languages/StaticHtml2Generator.java | 6 ++ .../languages/StaticHtmlGenerator.java | 6 ++ samples/html/index.html | 88 +++++++++---------- samples/html2/index.html | 2 +- 4 files changed, 57 insertions(+), 45 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 1979d0c1913..2907c1dfc43 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -65,6 +65,12 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi return "html2"; } + @Override + public String escapeText(String input) { + // newline escaping disabled for HTML documentation for markdown to work correctly + return input; + } + @Override public String getHelp() { return "Generates a static HTML file."; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 541bf98e6ad..2fe4cd7b665 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -60,6 +60,12 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig importMapping = new HashMap(); } + @Override + public String escapeText(String input) { + // newline escaping disabled for HTML documentation for markdown to work correctly + return input; + } + @Override public CodegenType getTag() { return CodegenType.DOCUMENTATION; diff --git a/samples/html/index.html b/samples/html/index.html index 425b46386d2..850fa5752d0 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -355,18 +355,18 @@ font-style: italic;

Example data

Content-Type: application/json
[ {
-  "tags" : [ {
-    "id" : 123456789,
-    "name" : "aeiou"
-  } ],
+  "photoUrls" : [ "aeiou" ],
+  "name" : "doggie",
   "id" : 123456789,
   "category" : {
-    "id" : 123456789,
-    "name" : "aeiou"
+    "name" : "aeiou",
+    "id" : 123456789
   },
-  "status" : "aeiou",
-  "name" : "doggie",
-  "photoUrls" : [ "aeiou" ]
+  "tags" : [ {
+    "name" : "aeiou",
+    "id" : 123456789
+  } ],
+  "status" : "aeiou"
 } ]

Produces

@@ -428,18 +428,18 @@ font-style: italic;

Example data

Content-Type: application/json
[ {
-  "tags" : [ {
-    "id" : 123456789,
-    "name" : "aeiou"
-  } ],
+  "photoUrls" : [ "aeiou" ],
+  "name" : "doggie",
   "id" : 123456789,
   "category" : {
-    "id" : 123456789,
-    "name" : "aeiou"
+    "name" : "aeiou",
+    "id" : 123456789
   },
-  "status" : "aeiou",
-  "name" : "doggie",
-  "photoUrls" : [ "aeiou" ]
+  "tags" : [ {
+    "name" : "aeiou",
+    "id" : 123456789
+  } ],
+  "status" : "aeiou"
 } ]

Produces

@@ -501,18 +501,18 @@ font-style: italic;

Example data

Content-Type: application/json
{
-  "tags" : [ {
-    "id" : 123456789,
-    "name" : "aeiou"
-  } ],
+  "photoUrls" : [ "aeiou" ],
+  "name" : "doggie",
   "id" : 123456789,
   "category" : {
-    "id" : 123456789,
-    "name" : "aeiou"
+    "name" : "aeiou",
+    "id" : 123456789
   },
-  "status" : "aeiou",
-  "name" : "doggie",
-  "photoUrls" : [ "aeiou" ]
+  "tags" : [ {
+    "name" : "aeiou",
+    "id" : 123456789
+  } ],
+  "status" : "aeiou"
 }

Produces

@@ -677,9 +677,9 @@ font-style: italic;

Example data

Content-Type: application/json
{
-  "message" : "aeiou",
   "code" : 123,
-  "type" : "aeiou"
+  "type" : "aeiou",
+  "message" : "aeiou"
 }

Produces

@@ -816,12 +816,12 @@ font-style: italic;

Example data

Content-Type: application/json
{
-  "id" : 123456789,
   "petId" : 123456789,
-  "complete" : true,
-  "status" : "aeiou",
   "quantity" : 123,
-  "shipDate" : "2000-01-23T04:56:07.000+00:00"
+  "id" : 123456789,
+  "shipDate" : "2000-01-23T04:56:07.000+00:00",
+  "complete" : true,
+  "status" : "aeiou"
 }

Produces

@@ -884,12 +884,12 @@ font-style: italic;

Example data

Content-Type: application/json
{
-  "id" : 123456789,
   "petId" : 123456789,
-  "complete" : true,
-  "status" : "aeiou",
   "quantity" : 123,
-  "shipDate" : "2000-01-23T04:56:07.000+00:00"
+  "id" : 123456789,
+  "shipDate" : "2000-01-23T04:56:07.000+00:00",
+  "complete" : true,
+  "status" : "aeiou"
 }

Produces

@@ -1103,14 +1103,14 @@ font-style: italic;

Example data

Content-Type: application/json
{
-  "id" : 123456789,
-  "lastName" : "aeiou",
-  "phone" : "aeiou",
-  "username" : "aeiou",
-  "email" : "aeiou",
-  "userStatus" : 123,
   "firstName" : "aeiou",
-  "password" : "aeiou"
+  "lastName" : "aeiou",
+  "password" : "aeiou",
+  "userStatus" : 123,
+  "phone" : "aeiou",
+  "id" : 123456789,
+  "email" : "aeiou",
+  "username" : "aeiou"
 }

Produces

diff --git a/samples/html2/index.html b/samples/html2/index.html index f454250971e..d9fba0bb5e5 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -9941,7 +9941,7 @@ try {
- Generated 2016-10-17T21:36:47.443+11:00 + Generated 2016-10-29T22:48:30.116+11:00
From 6963bf874877aa8a009079a89845c5a3a06ebea7 Mon Sep 17 00:00:00 2001 From: Robert Biehl Date: Tue, 1 Nov 2016 09:25:43 +0100 Subject: [PATCH 014/269] [Swift] Swift3 inheritance support (#4052) * Swift3 inheritance support * Mode inheritance support * Handle 204 No Content without crashing * Added some new reserved words for Swift (Error, URL) * Update swift3 pet store example * PR feedback fixes * removed unnecessary newline from Models.swift * removed unnecessary code comments * ~~public~~ open * Typo * Fix review feedback * fixed comment --- .../codegen/languages/Swift3Codegen.java | 60 ++++++++++++++++++- .../swift3/AlamofireImplementations.mustache | 9 ++- .../src/main/resources/swift3/Models.mustache | 28 +++++++-- .../src/main/resources/swift3/model.mustache | 13 ++-- .../Swaggers/AlamofireImplementations.swift | 9 ++- .../Classes/Swaggers/Models.swift | 40 +++++++++++++ .../Models/AdditionalPropertiesClass.swift | 2 +- .../Classes/Swaggers/Models/Animal.swift | 2 +- .../Classes/Swaggers/Models/ApiResponse.swift | 2 +- .../Models/ArrayOfArrayOfNumberOnly.swift | 2 +- .../Swaggers/Models/ArrayOfNumberOnly.swift | 2 +- .../Classes/Swaggers/Models/ArrayTest.swift | 2 +- .../Classes/Swaggers/Models/Cat.swift | 12 ++-- .../Classes/Swaggers/Models/Category.swift | 2 +- .../Classes/Swaggers/Models/Client.swift | 2 +- .../Classes/Swaggers/Models/Dog.swift | 12 ++-- .../Classes/Swaggers/Models/EnumArrays.swift | 2 +- .../Classes/Swaggers/Models/EnumTest.swift | 2 +- .../Classes/Swaggers/Models/FormatTest.swift | 2 +- .../Swaggers/Models/HasOnlyReadOnly.swift | 2 +- .../Classes/Swaggers/Models/List.swift | 2 +- .../Classes/Swaggers/Models/MapTest.swift | 2 +- ...opertiesAndAdditionalPropertiesClass.swift | 2 +- .../Swaggers/Models/Model200Response.swift | 2 +- .../Classes/Swaggers/Models/Name.swift | 2 +- .../Classes/Swaggers/Models/NumberOnly.swift | 2 +- .../Classes/Swaggers/Models/Order.swift | 2 +- .../Classes/Swaggers/Models/Pet.swift | 2 +- .../Swaggers/Models/ReadOnlyFirst.swift | 2 +- .../Classes/Swaggers/Models/Return.swift | 2 +- .../Swaggers/Models/SpecialModelName.swift | 2 +- .../Classes/Swaggers/Models/Tag.swift | 2 +- .../Classes/Swaggers/Models/User.swift | 2 +- 33 files changed, 177 insertions(+), 56 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index dd6b28702fd..d08dd89c585 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -102,7 +102,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { ); reservedWords = new HashSet<>( Arrays.asList( - "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", @@ -421,6 +421,21 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return name; } + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + if(codegenModel.description != null) { + codegenModel.imports.add("ApiModel"); + } + if (allDefinitions != null && codegenModel.parentSchema != null) { + final Model parentModel = allDefinitions.get(codegenModel.parentSchema); + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + codegenModel = Swift3Codegen.reconcileProperties(codegenModel, parentCodegenModel); + } + + return codegenModel; + } + @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. @@ -546,4 +561,47 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return input.replace("*/", "*_/").replace("/*", "/_*"); } + private static CodegenModel reconcileProperties(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // To support inheritance in this generator, we will analyze + // the parent and child models, look for properties that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the properties will be available via the parent. + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + codegenModel.allVars = new ArrayList(codegenProperties); + codegenModel.parentVars = parentCodegenModel.allVars; + + // Iterate over all of the parent model properties + boolean removedChildProperty = false; + + for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { + // Now that we have found a prop in the parent class, + // and search the child class for the same prop. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.equals(parentModelCodegenProperty)) { + // We found a property in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildProperty = true; + } + } + } + + if(removedChildProperty) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : null; + } + codegenModel.vars = codegenProperties; + } + + + return codegenModel; + } } diff --git a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache index 7cdc9411d03..03e421b7f10 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache @@ -100,7 +100,7 @@ open class AlamofireRequestBuilder: RequestBuilder { if stringResponse.result.isFailure { completion( nil, - ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) ) return } @@ -161,6 +161,13 @@ open class AlamofireRequestBuilder: RequestBuilder { return } + // handle HTTP 204 No Content + // NSNull would crash decoders + if response.response?.statusCode == 204 && response.result.value is NSNull{ + completion(nil, nil) + return; + } + if () is T { completion(Response(response: response.response!, body: (() as! T)), nil) return diff --git a/modules/swagger-codegen/src/main/resources/swift3/Models.mustache b/modules/swagger-codegen/src/main/resources/swift3/Models.mustache index a0e86595403..db33865ad4a 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/Models.mustache @@ -44,6 +44,15 @@ class Decoders { decoders[key] = { decoder($0) as AnyObject } } + static func decode(clazz: T.Type, discriminator: String, source: AnyObject) -> T { + let key = discriminator; + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + static func decode(clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } @@ -159,14 +168,21 @@ class Decoders { fatalError("Source \(source) is not convertible to enum type {{classname}}: Maybe swagger file is insufficient") {{/isEnum}} {{^isEnum}} -{{#vars.isEmpty}} +{{#allVars.isEmpty}} if let source = source as? {{dataType}} { return source } fatalError("Source \(source) is not convertible to typealias {{classname}}: Maybe swagger file is insufficient") -{{/vars.isEmpty}} -{{^vars.isEmpty}} +{{/allVars.isEmpty}} +{{^allVars.isEmpty}} let sourceDictionary = source as! [AnyHashable: Any] + {{#discriminator}} + // Check discriminator to support inheritance + if let discriminator = sourceDictionary["{{discriminator}}"] as? String, discriminator != "{{classname}}"{ + return Decoders.decode(clazz: {{classname}}.self, discriminator: discriminator, source: source) + } + {{/discriminator}} + {{#unwrapRequired}} let instance = {{classname}}({{#requiredVars}}{{^-first}}, {{/-first}}{{#isEnum}}{{name}}: {{classname}}.{{datatypeWithEnum}}(rawValue: (sourceDictionary["{{baseName}}"] as! {{datatype}}))! {{/isEnum}}{{^isEnum}}{{name}}: Decoders.decode(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"]! as AnyObject){{/isEnum}}{{/requiredVars}}) {{#optionalVars}}{{#isEnum}} @@ -178,15 +194,15 @@ class Decoders { {{/optionalVars}} {{/unwrapRequired}} {{^unwrapRequired}} - let instance = {{classname}}(){{#vars}}{{#isEnum}} + let instance = {{classname}}(){{#allVars}}{{#isEnum}} if let {{name}} = sourceDictionary["{{baseName}}"] as? {{datatype}} { {{^isContainer}} instance.{{name}} = {{classname}}.{{datatypeWithEnum}}(rawValue: ({{name}})){{/isContainer}}{{#isListContainer}} instance.{{name}} = {{name}}.map ({ {{classname}}.{{enumName}}(rawValue: $0)! }){{/isListContainer}}{{#isMapContainer}}//TODO: handle enum map scenario{{/isMapContainer}} }{{/isEnum}} - {{^isEnum}}instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}{{/vars}} + {{^isEnum}}instance.{{name}} = Decoders.decodeOptional(clazz: {{{baseType}}}.self, source: sourceDictionary["{{baseName}}"] as AnyObject?){{/isEnum}}{{/allVars}} {{/unwrapRequired}} return instance -{{/vars.isEmpty}} +{{/allVars.isEmpty}} {{/isEnum}} {{/isArrayModel}} }{{/model}} diff --git a/modules/swagger-codegen/src/main/resources/swift3/model.mustache b/modules/swagger-codegen/src/main/resources/swift3/model.mustache index d50f6d62360..6184fb54dfa 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/model.mustache @@ -26,7 +26,7 @@ public enum {{classname}}: {{dataType}} { public typealias {{classname}} = {{dataType}} {{/vars.isEmpty}} {{^vars.isEmpty}} -open class {{classname}}: JSONEncodable { +open class {{classname}}: {{#parent}}{{{parent}}}{{/parent}}{{^parent}}JSONEncodable{{/parent}} { {{#vars}} {{#isEnum}} public enum {{enumName}}: {{^isContainer}}{{datatype}}{{/isContainer}}{{#isContainer}}String{{/isContainer}} { {{#allowableValues}}{{#enumVars}} @@ -46,19 +46,20 @@ open class {{classname}}: JSONEncodable { {{/vars}} {{^unwrapRequired}} - public init() {} + {{^parent}}public init() {}{{/parent}} {{/unwrapRequired}} {{#unwrapRequired}} public init({{#allVars}}{{^-first}}, {{/-first}}{{name}}: {{#isEnum}}{{datatypeWithEnum}}{{/isEnum}}{{^isEnum}}{{datatype}}{{/isEnum}}{{^required}}?=nil{{/required}}{{/allVars}}) { - {{#allVars}} + {{#vars}} self.{{name}} = {{name}} - {{/allVars}} + {{/vars}} + {{#parent}}super.init({{#parentVars}}{{^-first}}, {{/-first}}{{name}}: {{name}}{{/parentVars}}){{/parent}} } {{/unwrapRequired}} // MARK: JSONEncodable - func encodeToJSON() -> Any { - var nillableDictionary = [String:Any?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}} + {{#parent}}override {{/parent}}open func encodeToJSON() -> Any { + var nillableDictionary = {{#parent}}super.encodeToJSON() as? [String:Any?] ?? {{/parent}}[String:Any?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}}{{#isInteger}} nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isInteger}}{{#isLong}} nillableDictionary["{{baseName}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isLong}}{{^isLong}}{{^isInteger}} nillableDictionary["{{baseName}}"] = self.{{name}}{{/isInteger}}{{/isLong}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 7cdc9411d03..03e421b7f10 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -100,7 +100,7 @@ open class AlamofireRequestBuilder: RequestBuilder { if stringResponse.result.isFailure { completion( nil, - ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error!) + ErrorResponse.Error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.result.error as Error!) ) return } @@ -161,6 +161,13 @@ open class AlamofireRequestBuilder: RequestBuilder { return } + // handle HTTP 204 No Content + // NSNull would crash decoders + if response.response?.statusCode == 204 && response.result.value is NSNull{ + completion(nil, nil) + return; + } + if () is T { completion(Response(response: response.response!, body: (() as! T)), nil) return diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift index f54e50205b0..cf0d7c99512 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -44,6 +44,15 @@ class Decoders { decoders[key] = { decoder($0) as AnyObject } } + static func decode(clazz: T.Type, discriminator: String, source: AnyObject) -> T { + let key = discriminator; + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + static func decode(clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } @@ -146,6 +155,7 @@ class Decoders { // Decoder for AdditionalPropertiesClass Decoders.addDecoder(clazz: AdditionalPropertiesClass.self) { (source: AnyObject) -> AdditionalPropertiesClass in let sourceDictionary = source as! [AnyHashable: Any] + let instance = AdditionalPropertiesClass() instance.mapProperty = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_property"] as AnyObject?) instance.mapOfMapProperty = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_of_map_property"] as AnyObject?) @@ -160,6 +170,11 @@ class Decoders { // Decoder for Animal Decoders.addDecoder(clazz: Animal.self) { (source: AnyObject) -> Animal in let sourceDictionary = source as! [AnyHashable: Any] + // Check discriminator to support inheritance + if let discriminator = sourceDictionary["className"] as? String, discriminator != "Animal"{ + return Decoders.decode(clazz: Animal.self, discriminator: discriminator, source: source) + } + let instance = Animal() instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) @@ -185,6 +200,7 @@ class Decoders { // Decoder for ApiResponse Decoders.addDecoder(clazz: ApiResponse.self) { (source: AnyObject) -> ApiResponse in let sourceDictionary = source as! [AnyHashable: Any] + let instance = ApiResponse() instance.code = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["code"] as AnyObject?) instance.type = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["type"] as AnyObject?) @@ -200,6 +216,7 @@ class Decoders { // Decoder for ArrayOfArrayOfNumberOnly Decoders.addDecoder(clazz: ArrayOfArrayOfNumberOnly.self) { (source: AnyObject) -> ArrayOfArrayOfNumberOnly in let sourceDictionary = source as! [AnyHashable: Any] + let instance = ArrayOfArrayOfNumberOnly() instance.arrayArrayNumber = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["ArrayArrayNumber"] as AnyObject?) return instance @@ -213,6 +230,7 @@ class Decoders { // Decoder for ArrayOfNumberOnly Decoders.addDecoder(clazz: ArrayOfNumberOnly.self) { (source: AnyObject) -> ArrayOfNumberOnly in let sourceDictionary = source as! [AnyHashable: Any] + let instance = ArrayOfNumberOnly() instance.arrayNumber = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["ArrayNumber"] as AnyObject?) return instance @@ -226,6 +244,7 @@ class Decoders { // Decoder for ArrayTest Decoders.addDecoder(clazz: ArrayTest.self) { (source: AnyObject) -> ArrayTest in let sourceDictionary = source as! [AnyHashable: Any] + let instance = ArrayTest() instance.arrayOfString = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_of_string"] as AnyObject?) instance.arrayArrayOfInteger = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["array_array_of_integer"] as AnyObject?) @@ -241,6 +260,7 @@ class Decoders { // Decoder for Cat Decoders.addDecoder(clazz: Cat.self) { (source: AnyObject) -> Cat in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Cat() instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) @@ -256,6 +276,7 @@ class Decoders { // Decoder for Category Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Category() instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?) @@ -270,6 +291,7 @@ class Decoders { // Decoder for Client Decoders.addDecoder(clazz: Client.self) { (source: AnyObject) -> Client in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Client() instance.client = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["client"] as AnyObject?) return instance @@ -283,6 +305,7 @@ class Decoders { // Decoder for Dog Decoders.addDecoder(clazz: Dog.self) { (source: AnyObject) -> Dog in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Dog() instance.className = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["className"] as AnyObject?) instance.color = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["color"] as AnyObject?) @@ -298,6 +321,7 @@ class Decoders { // Decoder for EnumArrays Decoders.addDecoder(clazz: EnumArrays.self) { (source: AnyObject) -> EnumArrays in let sourceDictionary = source as! [AnyHashable: Any] + let instance = EnumArrays() if let justSymbol = sourceDictionary["just_symbol"] as? String { instance.justSymbol = EnumArrays.JustSymbol(rawValue: (justSymbol)) @@ -333,6 +357,7 @@ class Decoders { // Decoder for EnumTest Decoders.addDecoder(clazz: EnumTest.self) { (source: AnyObject) -> EnumTest in let sourceDictionary = source as! [AnyHashable: Any] + let instance = EnumTest() if let enumString = sourceDictionary["enum_string"] as? String { instance.enumString = EnumTest.EnumString(rawValue: (enumString)) @@ -357,6 +382,7 @@ class Decoders { // Decoder for FormatTest Decoders.addDecoder(clazz: FormatTest.self) { (source: AnyObject) -> FormatTest in let sourceDictionary = source as! [AnyHashable: Any] + let instance = FormatTest() instance.integer = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["integer"] as AnyObject?) instance.int32 = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["int32"] as AnyObject?) @@ -382,6 +408,7 @@ class Decoders { // Decoder for HasOnlyReadOnly Decoders.addDecoder(clazz: HasOnlyReadOnly.self) { (source: AnyObject) -> HasOnlyReadOnly in let sourceDictionary = source as! [AnyHashable: Any] + let instance = HasOnlyReadOnly() instance.bar = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?) instance.foo = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["foo"] as AnyObject?) @@ -396,6 +423,7 @@ class Decoders { // Decoder for List Decoders.addDecoder(clazz: List.self) { (source: AnyObject) -> List in let sourceDictionary = source as! [AnyHashable: Any] + let instance = List() instance._123List = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["123-list"] as AnyObject?) return instance @@ -409,6 +437,7 @@ class Decoders { // Decoder for MapTest Decoders.addDecoder(clazz: MapTest.self) { (source: AnyObject) -> MapTest in let sourceDictionary = source as! [AnyHashable: Any] + let instance = MapTest() instance.mapMapOfString = Decoders.decodeOptional(clazz: Dictionary.self, source: sourceDictionary["map_map_of_string"] as AnyObject?) if let mapOfEnumString = sourceDictionary["map_of_enum_string"] as? [String:String] { //TODO: handle enum map scenario @@ -425,6 +454,7 @@ class Decoders { // Decoder for MixedPropertiesAndAdditionalPropertiesClass Decoders.addDecoder(clazz: MixedPropertiesAndAdditionalPropertiesClass.self) { (source: AnyObject) -> MixedPropertiesAndAdditionalPropertiesClass in let sourceDictionary = source as! [AnyHashable: Any] + let instance = MixedPropertiesAndAdditionalPropertiesClass() instance.uuid = Decoders.decodeOptional(clazz: UUID.self, source: sourceDictionary["uuid"] as AnyObject?) instance.dateTime = Decoders.decodeOptional(clazz: Date.self, source: sourceDictionary["dateTime"] as AnyObject?) @@ -440,6 +470,7 @@ class Decoders { // Decoder for Model200Response Decoders.addDecoder(clazz: Model200Response.self) { (source: AnyObject) -> Model200Response in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Model200Response() instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?) instance._class = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["class"] as AnyObject?) @@ -454,6 +485,7 @@ class Decoders { // Decoder for Name Decoders.addDecoder(clazz: Name.self) { (source: AnyObject) -> Name in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Name() instance.name = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["name"] as AnyObject?) instance.snakeCase = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["snake_case"] as AnyObject?) @@ -470,6 +502,7 @@ class Decoders { // Decoder for NumberOnly Decoders.addDecoder(clazz: NumberOnly.self) { (source: AnyObject) -> NumberOnly in let sourceDictionary = source as! [AnyHashable: Any] + let instance = NumberOnly() instance.justNumber = Decoders.decodeOptional(clazz: Double.self, source: sourceDictionary["JustNumber"] as AnyObject?) return instance @@ -483,6 +516,7 @@ class Decoders { // Decoder for Order Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Order() instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) instance.petId = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["petId"] as AnyObject?) @@ -504,6 +538,7 @@ class Decoders { // Decoder for Pet Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Pet() instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"] as AnyObject?) @@ -525,6 +560,7 @@ class Decoders { // Decoder for ReadOnlyFirst Decoders.addDecoder(clazz: ReadOnlyFirst.self) { (source: AnyObject) -> ReadOnlyFirst in let sourceDictionary = source as! [AnyHashable: Any] + let instance = ReadOnlyFirst() instance.bar = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["bar"] as AnyObject?) instance.baz = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["baz"] as AnyObject?) @@ -539,6 +575,7 @@ class Decoders { // Decoder for Return Decoders.addDecoder(clazz: Return.self) { (source: AnyObject) -> Return in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Return() instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"] as AnyObject?) return instance @@ -552,6 +589,7 @@ class Decoders { // Decoder for SpecialModelName Decoders.addDecoder(clazz: SpecialModelName.self) { (source: AnyObject) -> SpecialModelName in let sourceDictionary = source as! [AnyHashable: Any] + let instance = SpecialModelName() instance.specialPropertyName = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["$special[property.name]"] as AnyObject?) return instance @@ -565,6 +603,7 @@ class Decoders { // Decoder for Tag Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in let sourceDictionary = source as! [AnyHashable: Any] + let instance = Tag() instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"] as AnyObject?) @@ -579,6 +618,7 @@ class Decoders { // Decoder for User Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in let sourceDictionary = source as! [AnyHashable: Any] + let instance = User() instance.id = Decoders.decodeOptional(clazz: Int64.self, source: sourceDictionary["id"] as AnyObject?) instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"] as AnyObject?) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift index 17050f45a00..1d597c72542 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/AdditionalPropertiesClass.swift @@ -15,7 +15,7 @@ open class AdditionalPropertiesClass: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["map_property"] = self.mapProperty?.encodeToJSON() nillableDictionary["map_of_map_property"] = self.mapOfMapProperty?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift index 458b62ba7b1..bcb5136be44 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Animal.swift @@ -15,7 +15,7 @@ open class Animal: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["className"] = self.className nillableDictionary["color"] = self.color diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift index eba4c7542e5..20aaed5294c 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ApiResponse.swift @@ -16,7 +16,7 @@ open class ApiResponse: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["code"] = self.code?.encodeToJSON() nillableDictionary["type"] = self.type diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift index b02706d0c4a..6a549ca866b 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfArrayOfNumberOnly.swift @@ -14,7 +14,7 @@ open class ArrayOfArrayOfNumberOnly: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["ArrayArrayNumber"] = self.arrayArrayNumber?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift index 4ffbccbea0b..01ebd614c10 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayOfNumberOnly.swift @@ -14,7 +14,7 @@ open class ArrayOfNumberOnly: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["ArrayNumber"] = self.arrayNumber?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift index 0467b1fddb7..e344f141f80 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ArrayTest.swift @@ -16,7 +16,7 @@ open class ArrayTest: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["array_of_string"] = self.arrayOfString?.encodeToJSON() nillableDictionary["array_array_of_integer"] = self.arrayArrayOfInteger?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift index 2d7c09d8d8e..9c714f8e9fc 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Cat.swift @@ -8,18 +8,14 @@ import Foundation -open class Cat: JSONEncodable { - public var className: String? - public var color: String? +open class Cat: Animal { public var declawed: Bool? - public init() {} + // MARK: JSONEncodable - func encodeToJSON() -> Any { - var nillableDictionary = [String:Any?]() - nillableDictionary["className"] = self.className - nillableDictionary["color"] = self.color + override open func encodeToJSON() -> Any { + var nillableDictionary = super.encodeToJSON() as? [String:Any?] ?? [String:Any?]() nillableDictionary["declawed"] = self.declawed let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Category.swift index 3ee5bcf755d..8f97c2b302b 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Category.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -15,7 +15,7 @@ open class Category: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["name"] = self.name diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Client.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Client.swift index fca54db7f24..9b2a4ab2204 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Client.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Client.swift @@ -14,7 +14,7 @@ open class Client: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["client"] = self.client let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift index b5acdb2d8c3..7ce0453b30f 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Dog.swift @@ -8,18 +8,14 @@ import Foundation -open class Dog: JSONEncodable { - public var className: String? - public var color: String? +open class Dog: Animal { public var breed: String? - public init() {} + // MARK: JSONEncodable - func encodeToJSON() -> Any { - var nillableDictionary = [String:Any?]() - nillableDictionary["className"] = self.className - nillableDictionary["color"] = self.color + override open func encodeToJSON() -> Any { + var nillableDictionary = super.encodeToJSON() as? [String:Any?] ?? [String:Any?]() nillableDictionary["breed"] = self.breed let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift index 5cf7022f37b..1f40cde52f3 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumArrays.swift @@ -23,7 +23,7 @@ open class EnumArrays: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["just_symbol"] = self.justSymbol?.rawValue nillableDictionary["array_enum"] = self.arrayEnum?.map({$0.rawValue}).encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 4ffb9a0a665..03342500961 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -28,7 +28,7 @@ open class EnumTest: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["enum_string"] = self.enumString?.rawValue nillableDictionary["enum_integer"] = self.enumInteger?.rawValue diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift index 690ae992699..ffa7c28553a 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/FormatTest.swift @@ -26,7 +26,7 @@ open class FormatTest: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["integer"] = self.integer?.encodeToJSON() nillableDictionary["int32"] = self.int32?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift index 97d8559b453..4364dbaf776 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/HasOnlyReadOnly.swift @@ -15,7 +15,7 @@ open class HasOnlyReadOnly: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["bar"] = self.bar nillableDictionary["foo"] = self.foo diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/List.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/List.swift index 90ba954f6c1..7ce9ff47d4e 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/List.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/List.swift @@ -14,7 +14,7 @@ open class List: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["123-list"] = self._123List let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift index 224e811f428..0880b687148 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MapTest.swift @@ -19,7 +19,7 @@ open class MapTest: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["map_map_of_string"] = self.mapMapOfString?.encodeToJSON()//TODO: handle enum map scenario let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index b03ae51c5b6..a917131883a 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -16,7 +16,7 @@ open class MixedPropertiesAndAdditionalPropertiesClass: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["uuid"] = self.uuid?.encodeToJSON() nillableDictionary["dateTime"] = self.dateTime?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift index c2c561e61b1..3dcd6b09dc9 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Model200Response.swift @@ -16,7 +16,7 @@ open class Model200Response: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["name"] = self.name?.encodeToJSON() nillableDictionary["class"] = self._class diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Name.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Name.swift index 6cdfc2fc63d..9a271bdf8da 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Name.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Name.swift @@ -18,7 +18,7 @@ open class Name: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["name"] = self.name?.encodeToJSON() nillableDictionary["snake_case"] = self.snakeCase?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift index 33969777057..f1e50d03ed1 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/NumberOnly.swift @@ -14,7 +14,7 @@ open class NumberOnly: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["JustNumber"] = self.justNumber let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Order.swift index ff4a525c925..3eb64b90959 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Order.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -25,7 +25,7 @@ open class Order: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["petId"] = self.petId?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift index 245e34a29e9..08d61de5ab4 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -25,7 +25,7 @@ open class Pet: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["category"] = self.category?.encodeToJSON() diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift index 3643e9ee48b..00cabfb0859 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ReadOnlyFirst.swift @@ -15,7 +15,7 @@ open class ReadOnlyFirst: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["bar"] = self.bar nillableDictionary["baz"] = self.baz diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Return.swift index b90b0f1c427..f7e490008bc 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Return.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Return.swift @@ -15,7 +15,7 @@ open class Return: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["return"] = self._return?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift index 4092ffceb8b..9c84a306acb 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/SpecialModelName.swift @@ -14,7 +14,7 @@ open class SpecialModelName: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["$special[property.name]"] = self.specialPropertyName?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift index 6542c1208d8..e175e5aac35 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -15,7 +15,7 @@ open class Tag: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["name"] = self.name diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/User.swift index d4d299ce40c..c3887ebffc6 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/User.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -22,7 +22,7 @@ open class User: JSONEncodable { public init() {} // MARK: JSONEncodable - func encodeToJSON() -> Any { + open func encodeToJSON() -> Any { var nillableDictionary = [String:Any?]() nillableDictionary["id"] = self.id?.encodeToJSON() nillableDictionary["username"] = self.username From a5eff7e571cc22d4148ef0073824f35c8ceee342 Mon Sep 17 00:00:00 2001 From: scannerscan Date: Tue, 1 Nov 2016 19:36:56 +1100 Subject: [PATCH 015/269] Jdk6 jersey2 support (#4074) * hashCode and equals support for jdk6 for jersey2 * supportJava6 moved to the base abstract class to support server side code generation, supportJava6 flag was added to the server side model classes generators, licenseInfo ttemplate was added to JavaJaxRS section, javaJaxRS templates jdk6 suport was added, shouldOverride method was commented out to allow server classes to be overriden - what if new methods or signatures changes? * fix for the build. * supportJava6 moved to the base abstract class to support server side code generation, supportJava6 flag was added to the server side model classes generators, licenseInfo ttemplate was added to JavaJaxRS section, javaJaxRS templates jdk6 suport was added, shouldOverride method was commented out to allow server classes to be overriden - what if new methods or signatures changes? * fix for the build. * Merge remote-tracking branch 'remotes/origin/master' into jdk6-jersey2-support Conflicts: modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java modules/swagger-codegen/src/main/resources/Java/pom.mustache * add msf4j author * [Java] Fix outputFolder in java-related server stub generators (#4076) * fix outputFolder in java-related server stub generator * fix style in JavaJAXRSCXFCDIServerCodegen * hashCode and equals support for jdk6 for jersey2 * supportJava6 moved to the base abstract class to support server side code generation, supportJava6 flag was added to the server side model classes generators, licenseInfo ttemplate was added to JavaJaxRS section, javaJaxRS templates jdk6 suport was added, shouldOverride method was commented out to allow server classes to be overriden - what if new methods or signatures changes? * fix for the build. * supportJava6 moved to the base abstract class to support server side code generation, supportJava6 flag was added to the server side model classes generators, licenseInfo ttemplate was added to JavaJaxRS section, javaJaxRS templates jdk6 suport was added, shouldOverride method was commented out to allow server classes to be overriden - what if new methods or signatures changes? * Merge remote-tracking branch 'remotes/origin/master' into jdk6-jersey2-support Conflicts: modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java modules/swagger-codegen/src/main/resources/Java/pom.mustache * Merge remote-tracking branch 'remotes/origin/master' into jdk6-jersey2-support Conflicts: modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java modules/swagger-codegen/src/main/resources/Java/pom.mustache --- .../languages/AbstractJavaCodegen.java | 12 ++++++ .../AbstractJavaJAXRSServerCodegen.java | 6 --- .../codegen/languages/JavaClientCodegen.java | 19 ++------ .../languages/JavaJAXRSSpecServerCodegen.java | 1 - .../languages/JavaJerseyServerCodegen.java | 3 +- .../src/main/resources/Java/pom.mustache | 1 + .../resources/JavaJaxRS/licenseInfo.mustache | 23 ++++++++++ .../main/resources/JavaJaxRS/model.mustache | 14 +++--- .../resources/JavaJaxRS/modelEnum.mustache | 43 +++++++++++++++++++ .../main/resources/JavaJaxRS/pojo.mustache | 25 +++++++++++ .../src/main/resources/JavaJaxRS/pom.mustache | 25 +++++++++++ .../codegen/jaxrs/JaxRSServerOptionsTest.java | 2 + .../options/JaxRSServerOptionsProvider.java | 1 + 13 files changed, 146 insertions(+), 29 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/licenseInfo.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/modelEnum.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 9bd2484b474..7d88ec93157 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -45,6 +45,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public static final String FULL_JAVA_UTIL = "fullJavaUtil"; public static final String DEFAULT_LIBRARY = ""; public static final String DATE_LIBRARY = "dateLibrary"; + public static final String SUPPORT_JAVA6 = "supportJava6"; protected String dateLibrary = "joda"; protected String invokerPackage = "io.swagger"; @@ -63,6 +64,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected boolean hideGenerationTimestamp = false; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected boolean supportJava6= false; public AbstractJavaCodegen() { super(); @@ -139,6 +141,12 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(SUPPORT_JAVA6)) { + this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString())); + } + additionalProperties.put(SUPPORT_JAVA6, supportJava6); + + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { @@ -934,6 +942,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } return sb.toString(); } + public void setSupportJava6(boolean value) { + this.supportJava6 = value; + } + public String toRegularExpression(String pattern) { return escapeText(pattern); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 9ed96485119..de0812c40f8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -200,10 +200,4 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen private String implFileFolder(String output) { return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); } - - @Override - public boolean shouldOverwrite(String filename) { - return super.shouldOverwrite(filename) && !filename.endsWith("ServiceImpl.java") && !filename.endsWith("ServiceFactory.java"); - } - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 6a472c39646..a2632bd036c 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 @@ -17,7 +17,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida public static final String USE_RX_JAVA = "useRxJava"; public static final String PARCELABLE_MODEL = "parcelableModel"; - public static final String SUPPORT_JAVA6 = "supportJava6"; public static final String RETROFIT_1 = "retrofit"; public static final String RETROFIT_2 = "retrofit2"; @@ -25,7 +24,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; protected boolean parcelableModel = false; - protected boolean supportJava6= false; protected boolean useBeanValidation = false; public JavaClientCodegen() { @@ -85,20 +83,15 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida } // put the boolean value back to PARCELABLE_MODEL in additionalProperties additionalProperties.put(PARCELABLE_MODEL, parcelableModel); - + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { boolean useBeanValidationProp = Boolean.valueOf(additionalProperties.get(USE_BEANVALIDATION).toString()); this.setUseBeanValidation(useBeanValidationProp); - + // write back as boolean additionalProperties.put(USE_BEANVALIDATION, useBeanValidationProp); } - if (additionalProperties.containsKey(SUPPORT_JAVA6)) { - this.setSupportJava6(Boolean.valueOf(additionalProperties.get(SUPPORT_JAVA6).toString())); - } - additionalProperties.put(SUPPORT_JAVA6, supportJava6); - final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); @@ -196,7 +189,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida operation.returnType = "Void"; } if (usesRetrofit2Library() && StringUtils.isNotEmpty(operation.path) && operation.path.startsWith("/")) - operation.path = operation.path.substring(1); + operation.path = operation.path.substring(1); } } } @@ -244,7 +237,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida } return objs; } - + public void setUseRxJava(boolean useRxJava) { this.useRxJava = useRxJava; } @@ -253,10 +246,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida this.parcelableModel = parcelableModel; } - public void setSupportJava6(boolean value) { - this.supportJava6 = value; - } - public void setUseBeanValidation(boolean useBeanValidation) { this.useBeanValidation = useBeanValidation; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 4e1f388e8a4..7c8d03c1375 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -24,7 +24,6 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen public JavaJAXRSSpecServerCodegen() { super(); - sourceFolder = "src/main/java"; invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; outputFolder = "generated-code/JavaJaxRS-Spec"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index d09bb34990e..b8aef14410b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -44,7 +44,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { library.setDefault(DEFAULT_LIBRARY); cliOptions.add(library); - + cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1/2 library.")); } @Override @@ -110,6 +110,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); } + @Override public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 78225ad7599..9bd93ccd5e9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -180,6 +180,7 @@ migbase64 2.2 + {{#supportJava6}} org.apache.commons diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/licenseInfo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/licenseInfo.mustache new file mode 100644 index 00000000000..26b9876c7e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/licenseInfo.mustache @@ -0,0 +1,23 @@ +/* + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index d52b90c8bec..b84bfee6a85 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -1,6 +1,13 @@ +{{>licenseInfo}} + package {{package}}; +{{^supportJava6}} import java.util.Objects; +{{/supportJava6}} +{{#supportJava6}} +import org.apache.commons.lang3.ObjectUtils; +{{/supportJava6}} {{#imports}}import {{import}}; {{/imports}} {{#serializableModel}} @@ -9,11 +16,6 @@ import java.io.Serializable; {{#models}} {{#model}} -{{#isEnum}} -{{>enumOuterClass}} -{{/isEnum}} -{{^isEnum}} -{{>pojo}} -{{/isEnum}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>pojo}}{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/modelEnum.mustache new file mode 100644 index 00000000000..baddbae19be --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/modelEnum.mustache @@ -0,0 +1,43 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +{{#jackson}} + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +{{/jackson}} +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index 6e5c1b74115..f3a36ecc387 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -79,6 +79,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/vars}} +{{^supportJava6}} @Override public boolean equals(java.lang.Object o) { if (this == o) { @@ -99,6 +100,30 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); } +{{/supportJava6}} +{{#supportJava6}} + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}ObjectUtils.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return true;{{/hasVars}} + } + + @Override + public int hashCode() { + return ObjectUtils.hashCodeMulti({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + } + +{{/supportJava6}} + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index d764934cf77..03582826a58 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -124,6 +124,27 @@ jersey-media-multipart ${jersey2-version} + + + com.brsanthu + migbase64 + 2.2 + + + {{#supportJava6}} + + org.apache.commons + commons-lang3 + ${commons_lang3_version} + + + + commons-io + commons-io + ${commons_io_version} + + {{/supportJava6}} + @@ -141,6 +162,10 @@ 1.5.9 9.2.9.v20150224 2.22.2 + {{#supportJava6}} + 2.5 + 3.5 + {{/supportJava6}} 4.12 1.1.7 2.5 diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index 7753c8e45da..8c6c7149f9b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -54,6 +54,8 @@ public class JaxRSServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setDateLibrary("joda"); times = 1; + clientCodegen.setSupportJava6(false); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index 230084c2ec9..3db594f94b8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -39,6 +39,7 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); builder.put(CodegenConstants.IMPL_FOLDER, IMPL_FOLDER_VALUE) .put(JavaClientCodegen.DATE_LIBRARY, "joda") //java.lang.IllegalArgumentException: Multiple entries with same key: dateLibrary=joda and dateLibrary=joda + .put(JavaClientCodegen.SUPPORT_JAVA6, "false") .put("title", "Test title") .put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) From c2780abd70a3519c40da1ab21bd7de6ce7ed2188 Mon Sep 17 00:00:00 2001 From: Maciej Date: Tue, 1 Nov 2016 05:02:40 -0400 Subject: [PATCH 016/269] fixing issue#4037 - ts ng2 response type is always json (#4060) * fixing issue#4037 - default response is always json * updated documentation for new method * updated comment for new method --- .../typescript-angular2/api.mustache | 23 ++++- .../typescript-angular2/default/api/PetApi.ts | 89 ++++++++++++++----- .../default/api/StoreApi.ts | 47 ++++++++-- .../default/api/UserApi.ts | 79 ++++++++++++---- .../typescript-angular2/npm/README.md | 4 +- .../typescript-angular2/npm/api/PetApi.ts | 89 ++++++++++++++----- .../typescript-angular2/npm/api/StoreApi.ts | 47 ++++++++-- .../typescript-angular2/npm/api/UserApi.ts | 79 ++++++++++++---- .../typescript-angular2/npm/package.json | 2 +- 9 files changed, 364 insertions(+), 95 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 6980d8f7821..00a013f5675 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -34,6 +34,21 @@ export class {{classname}} { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } {{#operation}} /** @@ -157,9 +172,13 @@ export class {{classname}} { {{#hasFormParams}} body: formParams.toString(), {{/hasFormParams}} - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 492423eb3f6..f91faccdd65 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -51,6 +51,21 @@ export class PetApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Add a new pet to the store @@ -225,9 +240,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -272,9 +291,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -317,9 +340,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -362,9 +389,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -395,17 +426,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } @@ -413,9 +444,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -459,9 +494,13 @@ export class PetApi { method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -518,9 +557,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -577,9 +620,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 38d67411809..e5382d97b05 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -51,6 +51,21 @@ export class StoreApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Delete purchase order by ID @@ -149,9 +164,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -189,9 +208,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -229,9 +252,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -267,9 +294,13 @@ export class StoreApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 9ba9abd4079..a3f14b23790 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -51,6 +51,21 @@ export class UserApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Create user @@ -213,9 +228,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -251,9 +270,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -289,9 +312,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -329,9 +356,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -369,9 +400,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -412,9 +447,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -447,9 +486,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -490,9 +533,13 @@ export class UserApi { method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 6fb4d320d57..d5d17b9074d 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609212006 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201610271623 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201609212006 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201610271623 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 492423eb3f6..f91faccdd65 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -51,6 +51,21 @@ export class PetApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Add a new pet to the store @@ -225,9 +240,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -272,9 +291,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -317,9 +340,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -362,9 +389,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -395,17 +426,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } @@ -413,9 +444,13 @@ export class PetApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -459,9 +494,13 @@ export class PetApi { method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -518,9 +557,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -577,9 +620,13 @@ export class PetApi { method: RequestMethod.Post, headers: headers, body: formParams.toString(), - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 38d67411809..e5382d97b05 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -51,6 +51,21 @@ export class StoreApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Delete purchase order by ID @@ -149,9 +164,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -189,9 +208,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -229,9 +252,13 @@ export class StoreApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -267,9 +294,13 @@ export class StoreApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 9ba9abd4079..a3f14b23790 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -51,6 +51,21 @@ export class UserApi { this.configuration = configuration; } } + + /** + * + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object + */ + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } /** * Create user @@ -213,9 +228,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -251,9 +270,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -289,9 +312,13 @@ export class UserApi { method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -329,9 +356,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -369,9 +400,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -412,9 +447,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -447,9 +486,13 @@ export class UserApi { let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } @@ -490,9 +533,13 @@ export class UserApi { method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 - search: queryParameters, - responseType: ResponseContentType.Json + search: queryParameters }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } return this.http.request(path, requestOptions); } diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index f5386456da9..0bd97a1b43c 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201609212006", + "version": "0.0.1-SNAPSHOT.201610271623", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 0c1b1aa7494be70a599ea1a6285ea4b61f16851a Mon Sep 17 00:00:00 2001 From: Nick Maynard Date: Tue, 1 Nov 2016 09:34:28 +0000 Subject: [PATCH 017/269] Add Checkstyle to POM with Google settings advice (#4047) * Add Checkstyle to POM with Google settings advice * Add note re. changes for swagger-codegen * Use Checkstyle 6.19 - v7 removed JDK 7 runtime support * Add a link to the original config --- google_checkstyle.xml | 207 ++++++++++++++++++++++++++++++++++++++++++ pom.xml | 31 ++++++- 2 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 google_checkstyle.xml diff --git a/google_checkstyle.xml b/google_checkstyle.xml new file mode 100644 index 00000000000..a954a98c116 --- /dev/null +++ b/google_checkstyle.xml @@ -0,0 +1,207 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index aa94f36983e..bb277a2a6bf 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - + org.sonatype.oss oss-parent @@ -68,6 +67,34 @@ target ${project.artifactId}-${project.version} + + org.apache.maven.plugins + maven-checkstyle-plugin + 2.17 + + + validate + validate + + google_checkstyle.xml + UTF-8 + true + true + false + + + check + + + + + + com.puppycrawl.tools + checkstyle + 6.19 + + + org.apache.maven.plugins maven-surefire-plugin From 5c53513a30d557eb651d34595f240fe21fbb1931 Mon Sep 17 00:00:00 2001 From: Cliffano Subagio Date: Tue, 1 Nov 2016 21:21:53 +1100 Subject: [PATCH 018/269] [python] Add packageUrl option, replacing infoUrl in setup.py (#4101) * [python] Add packageUrl option, replacing infoUrl in setup.py . * [python] Regenerate Python petstore sample. * [python] Regenerate Python petstore security test sample. --- .../languages/PythonClientCodegen.java | 40 ++++-- .../src/main/resources/python/setup.mustache | 4 +- .../options/PythonClientOptionsProvider.java | 5 +- .../python/PythonClientOptionsTest.java | 2 + .../petstore-security-test/python/README.md | 28 ++-- .../python/docs/FakeApi.md | 25 ++-- .../python/docs/ModelReturn.md | 2 +- .../python/petstore_api/__init__.py | 8 +- .../python/petstore_api/api_client.py | 121 +++++++++++------- .../python/petstore_api/apis/fake_api.py | 46 ++++--- .../python/petstore_api/configuration.py | 27 ++-- .../python/petstore_api/models/__init__.py | 8 +- .../petstore_api/models/model_return.py | 13 +- .../python/petstore_api/rest.py | 43 ++++--- .../petstore-security-test/python/setup.py | 17 +-- samples/client/petstore/python/setup.py | 1 + 16 files changed, 221 insertions(+), 169 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index f0e9814fb12..3d838c22c7f 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -21,13 +21,16 @@ import java.util.Map; import org.apache.commons.lang3.StringUtils; public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { + public static final String PACKAGE_URL = "packageUrl"; + protected String packageName; protected String packageVersion; + protected String packageUrl; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; - + protected Map regexModifiers; - + private String testFolder; public PythonClientCodegen() { @@ -40,18 +43,18 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig modelPackage = "models"; apiPackage = "api"; outputFolder = "generated-code" + File.separatorChar + "python"; - + modelTemplateFiles.put("model.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py"); - + modelTestTemplateFiles.put("model_test.mustache", ".py"); apiTestTemplateFiles.put("api_test.mustache", ".py"); - + embeddedTemplateDir = templateDir = "python"; modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - + testFolder = "test"; languageSpecificPrimitives.clear(); @@ -98,7 +101,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try", "self")); - + regexModifiers = new HashMap(); regexModifiers.put('i', "IGNORECASE"); regexModifiers.put('l', "LOCALE"); @@ -112,6 +115,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig .defaultValue("swagger_client")); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") .defaultValue("1.0.0")); + cliOptions.add(new CliOption(PACKAGE_URL, "python package URL.")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") @@ -156,6 +160,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + if (additionalProperties.containsKey(PACKAGE_URL)) { + setPackageUrl((String) additionalProperties.get(PACKAGE_URL)); + } + String swaggerFolder = packageName; modelPackage = swaggerFolder + File.separatorChar + "models"; @@ -163,12 +171,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("LICENSE", "", "LICENSE")); - + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); - + supportingFiles.add(new SupportingFile("api_client.mustache", swaggerFolder, "api_client.py")); supportingFiles.add(new SupportingFile("rest.mustache", swaggerFolder, "rest.py")); supportingFiles.add(new SupportingFile("configuration.mustache", swaggerFolder, "configuration.py")); @@ -187,7 +195,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig private static String dropDots(String str) { return str.replaceAll("\\.", "_"); } - + @Override public void postProcessParameter(CodegenParameter parameter){ postProcessPattern(parameter.pattern, parameter.vendorExtensions); @@ -267,7 +275,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public String toApiDocFilename(String name) { return toApiName(name); } - + @Override public String apiFileFolder() { @@ -278,7 +286,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public String modelFileFolder() { return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); } - + @Override public String apiTestFileFolder() { return outputFolder + File.separatorChar + testFolder; @@ -419,7 +427,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // PhoneNumber => phone_number return underscore(dropDots(name)); } - + @Override public String toModelTestFilename(String name) { return "test_" + toModelFilename(name); @@ -433,7 +441,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig // e.g. PhoneNumberApi.rb => phone_number_api.rb return underscore(name) + "_api"; } - + @Override public String toApiTestFilename(String name) { return "test_" + toApiFilename(name); @@ -480,6 +488,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig this.packageVersion = packageVersion; } + public void setPackageUrl(String packageUrl) { + this.packageUrl = packageUrl; + } + /** * Generate Python package name from String `packageName` * diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index f46265995fa..45606bf9474 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -22,7 +22,7 @@ setup( version=VERSION, description="{{appName}}", author_email="{{infoEmail}}", - url="{{infoUrl}}", + url="{{packageUrl}}", keywords=["Swagger", "{{appName}}"], install_requires=REQUIRES, packages=find_packages(), @@ -31,4 +31,4 @@ setup( {{appDescription}} """ ) -{{/hasMore}}{{/apis}}{{/apiInfo}} \ No newline at end of file +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java index ccdb38d7bab..7ad1a05752a 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PythonClientOptionsProvider.java @@ -1,6 +1,7 @@ package io.swagger.codegen.options; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.PythonClientCodegen; import com.google.common.collect.ImmutableMap; @@ -9,6 +10,7 @@ import java.util.Map; public class PythonClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_client_python"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String PACKAGE_URL_VALUE = ""; @Override public String getLanguage() { @@ -18,7 +20,8 @@ public class PythonClientOptionsProvider implements OptionsProvider { @Override public Map createOptions() { ImmutableMap.Builder builder = new ImmutableMap.Builder(); - return builder.put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) + return builder.put(PythonClientCodegen.PACKAGE_URL, PACKAGE_URL_VALUE) + .put(CodegenConstants.PACKAGE_NAME, PACKAGE_NAME_VALUE) .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java index 2682200e60a..80fc53ac993 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonClientOptionsTest.java @@ -30,6 +30,8 @@ public class PythonClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setPackageVersion(PythonClientOptionsProvider.PACKAGE_VERSION_VALUE); times = 1; + clientCodegen.setPackageUrl(PythonClientOptionsProvider.PACKAGE_URL_VALUE); + times = 1; }}; } } diff --git a/samples/client/petstore-security-test/python/README.md b/samples/client/petstore-security-test/python/README.md index e0b043e4fe0..9f90aa1d071 100644 --- a/samples/client/petstore-security-test/python/README.md +++ b/samples/client/petstore-security-test/python/README.md @@ -1,11 +1,10 @@ # petstore_api -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- This Python package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 */ ' \" =end +- API version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r - Package version: 1.0.0 -- Build date: 2016-06-28T16:59:35.203+08:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -46,29 +45,30 @@ import petstore_api Please follow the [installation procedure](#installation--usage) and then run the following: ```python +from __future__ import print_function import time import petstore_api from petstore_api.rest import ApiException from pprint import pprint # create an instance of the API class -api_instance = petstore_api.FakeApi -test_code_inject____end = 'test_code_inject____end_example' # str | To test code injection */ ' \" =end (optional) +api_instance = petstore_api.FakeApi() +test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \" =end -- \\r\\n \\n \\r (optional) try: - # To test code injection */ ' \" =end - api_instance.test_code_inject____end(test_code_inject____end=test_code_inject____end) + # To test code injection */ ' \" =end -- \\r\\n \\n \\r + api_instance.test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r) except ApiException as e: - print "Exception when calling FakeApi->test_code_inject____end: %s\n" % e + print("Exception when calling FakeApi->test_code_inject____end__rn_n_r: %s\n" % e) ``` ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io */ ' " =end/v2 */ ' " =end* +All URIs are relative to *https://petstore.swagger.io */ ' \" =end -- \\r\\n \\n \\r/v2 */ ' \" =end -- \\r\\n \\n \\r* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**test_code_inject____end**](docs/FakeApi.md#test_code_inject____end) | **PUT** /fake | To test code injection */ ' \" =end +*FakeApi* | [**test_code_inject____end__rn_n_r**](docs/FakeApi.md#test_code_inject____end__rn_n_r) | **PUT** /fake | To test code injection */ ' \" =end -- \\r\\n \\n \\r ## Documentation For Models @@ -82,7 +82,7 @@ Class | Method | HTTP request | Description ## api_key - **Type**: API key -- **API key parameter name**: api_key */ ' " =end +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r - **Location**: HTTP header ## petstore_auth @@ -91,11 +91,11 @@ Class | Method | HTTP request | Description - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - **write:pets**: modify pets in your account */ ' " =end - - **read:pets**: read your pets */ ' " =end + - **write:pets**: modify pets in your account */ ' \" =end -- \\r\\n \\n \\r + - **read:pets**: read your pets */ ' \" =end -- \\r\\n \\n \\r ## Author -apiteam@swagger.io */ ' \" =end +apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r diff --git a/samples/client/petstore-security-test/python/docs/FakeApi.md b/samples/client/petstore-security-test/python/docs/FakeApi.md index fb3ca4b4d73..c3f15c2b4b7 100644 --- a/samples/client/petstore-security-test/python/docs/FakeApi.md +++ b/samples/client/petstore-security-test/python/docs/FakeApi.md @@ -1,19 +1,20 @@ # petstore_api.FakeApi -All URIs are relative to *https://petstore.swagger.io */ ' " =end/v2 */ ' " =end* +All URIs are relative to *https://petstore.swagger.io */ ' \" =end -- \\r\\n \\n \\r/v2 */ ' \" =end -- \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_code_inject____end**](FakeApi.md#test_code_inject____end) | **PUT** /fake | To test code injection */ ' \" =end +[**test_code_inject____end__rn_n_r**](FakeApi.md#test_code_inject____end__rn_n_r) | **PUT** /fake | To test code injection */ ' \" =end -- \\r\\n \\n \\r -# **test_code_inject____end** -> test_code_inject____end(test_code_inject____end=test_code_inject____end) +# **test_code_inject____end__rn_n_r** +> test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r) -To test code injection */ ' \" =end +To test code injection */ ' \" =end -- \\r\\n \\n \\r ### Example ```python +from __future__ import print_statement import time import petstore_api from petstore_api.rest import ApiException @@ -21,20 +22,20 @@ from pprint import pprint # create an instance of the API class api_instance = petstore_api.FakeApi() -test_code_inject____end = 'test_code_inject____end_example' # str | To test code injection */ ' \" =end (optional) +test_code_inject____end____rn_n_r = 'test_code_inject____end____rn_n_r_example' # str | To test code injection */ ' \" =end -- \\r\\n \\n \\r (optional) try: - # To test code injection */ ' \" =end - api_instance.test_code_inject____end(test_code_inject____end=test_code_inject____end) + # To test code injection */ ' \" =end -- \\r\\n \\n \\r + api_instance.test_code_inject____end__rn_n_r(test_code_inject____end____rn_n_r=test_code_inject____end____rn_n_r) except ApiException as e: - print "Exception when calling FakeApi->test_code_inject____end: %s\n" % e + print("Exception when calling FakeApi->test_code_inject____end__rn_n_r: %s\n" % e) ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject____end** | **str**| To test code injection */ ' \" =end | [optional] + **test_code_inject____end____rn_n_r** | **str**| To test code injection */ ' \" =end -- \\r\\n \\n \\r | [optional] ### Return type @@ -46,8 +47,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ " =end - - **Accept**: application/json, */ " =end + - **Content-Type**: application/json, */ \" =end -- + - **Accept**: application/json, */ \" =end -- [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/python/docs/ModelReturn.md b/samples/client/petstore-security-test/python/docs/ModelReturn.md index 8d45b479ac4..ad498239b57 100644 --- a/samples/client/petstore-security-test/python/docs/ModelReturn.md +++ b/samples/client/petstore-security-test/python/docs/ModelReturn.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **int** | property description */ ' \" =end | [optional] +**_return** | **int** | property description */ ' \" =end -- \\r\\n \\n \\r | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/python/petstore_api/__init__.py b/samples/client/petstore-security-test/python/petstore_api/__init__.py index 64a6832a631..6bfb00016ef 100644 --- a/samples/client/petstore-security-test/python/petstore_api/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/__init__.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/python/petstore_api/api_client.py b/samples/client/petstore-security-test/python/petstore_api/api_client.py index 2521ba15fd3..adf66173dbc 100644 --- a/samples/client/petstore-security-test/python/petstore_api/api_client.py +++ b/samples/client/petstore-security-test/python/petstore_api/api_client.py @@ -19,17 +19,15 @@ Copyright 2016 SmartBear Software """ from __future__ import absolute_import + from . import models from .rest import RESTClientObject from .rest import ApiException import os import re -import sys -import urllib import json import mimetypes -import random import tempfile import threading @@ -37,14 +35,8 @@ from datetime import datetime from datetime import date # python 2 and python 3 compatibility library -from six import iteritems - -try: - # for python3 - from urllib.parse import quote -except ImportError: - # for python2 - from urllib import quote +from six import PY3, integer_types, iteritems, text_type +from six.moves.urllib.parse import quote from .configuration import Configuration @@ -103,34 +95,40 @@ class ApiClient(object): def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): - # headers parameters + # header parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) + header_params = dict(self.parameters_to_tuples(header_params, + collection_formats)) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - for k, v in iteritems(path_params): - replacement = quote(str(self.to_path_value(v))) - resource_path = resource_path.\ - replace('{' + k + '}', replacement) + path_params = self.parameters_to_tuples(path_params, + collection_formats) + for k, v in path_params: + resource_path = resource_path.replace( + '{%s}' % k, quote(str(v))) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - query_params = {k: self.to_path_value(v) - for k, v in iteritems(query_params)} + query_params = self.parameters_to_tuples(query_params, + collection_formats) # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + post_params = self.parameters_to_tuples(post_params, + collection_formats) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) @@ -159,31 +157,16 @@ class ApiClient(object): if callback: callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return ( deserialized_data ); + return (deserialized_data) else: return (deserialized_data, response_data.status, response_data.getheaders()) - - - def to_path_value(self, obj): - """ - Takes value and turn it into a string suitable for inclusion in - the path, by url-encoding. - - :param obj: object or string value. - - :return string: quoted value. - """ - if type(obj) == list: - return ','.join(obj) - else: - return str(obj) def sanitize_for_serialization(self, obj): """ Builds a JSON POST object. If obj is None, return None. - If obj is str, int, float, bool, return directly. + If obj is str, int, long, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. @@ -193,9 +176,7 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) - if sys.version_info < (3, 0): - types = types + (unicode,) + types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): @@ -203,6 +184,9 @@ class ApiClient(object): elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] + elif isinstance(obj, tuple): + return tuple(self.sanitize_for_serialization(sub_obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: @@ -227,7 +211,7 @@ class ApiClient(object): :param response: RESTResponse object to be deserialized. :param response_type: class literal for - deserialzied object, or string of class name. + deserialized object, or string of class name. :return: deserialized object. """ @@ -272,11 +256,13 @@ class ApiClient(object): if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) + elif klass == 'long': + klass = int if PY3 else long # for model types else: klass = eval('models.' + klass) - if klass in [int, float, str, bool]: + if klass in integer_types or klass in (float, str, bool): return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -290,7 +276,8 @@ class ApiClient(object): def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, - response_type=None, auth_settings=None, callback=None, _return_http_data_only=None): + response_type=None, auth_settings=None, callback=None, + _return_http_data_only=None, collection_formats=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -312,6 +299,8 @@ class ApiClient(object): If provide this parameter, the request will be called asynchronously. :param _return_http_data_only: response data without head status code and headers + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. :return: If provide parameter callback, the request will be called asynchronously. @@ -323,7 +312,8 @@ class ApiClient(object): return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, - response_type, auth_settings, callback, _return_http_data_only) + response_type, auth_settings, callback, + _return_http_data_only, collection_formats) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -331,7 +321,8 @@ class ApiClient(object): header_params, body, post_params, files, response_type, auth_settings, - callback,_return_http_data_only)) + callback, _return_http_data_only, + collection_formats)) thread.start() return thread @@ -379,10 +370,41 @@ class ApiClient(object): body=body) else: raise ValueError( - "http method must be `GET`, `HEAD`," + "http method must be `GET`, `HEAD`, `OPTIONS`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) + def parameters_to_tuples(self, params, collection_formats): + """ + Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: Parameters as list of tuples, collections formatted + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in iteritems(params) if isinstance(params, dict) else params: + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(str(value) for value in v))) + else: + new_params.append((k, v)) + return new_params + def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. @@ -450,7 +472,7 @@ class ApiClient(object): Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters dict to be updated. + :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() @@ -466,7 +488,7 @@ class ApiClient(object): elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': - querys[auth_setting['key']] = auth_setting['value'] + querys.append((auth_setting['key'], auth_setting['value'])) else: raise ValueError( 'Authentication token must be in `query` or `header`' @@ -505,7 +527,7 @@ class ApiClient(object): :param data: str. :param klass: class literal. - :return: int, float, str, bool. + :return: int, long, float, str, bool. """ try: value = klass(data) @@ -573,6 +595,9 @@ class ApiClient(object): """ instance = klass() + if not instance.swagger_types: + return data + for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ diff --git a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py index 8e2719f3ea7..b2a58f84e7b 100644 --- a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); @@ -51,9 +51,9 @@ class FakeApi(object): config.api_client = ApiClient() self.api_client = config.api_client - def test_code_inject____end(self, **kwargs): + def test_code_inject____end__rn_n_r(self, **kwargs): """ - To test code injection */ ' \" =end + To test code injection */ ' \" =end -- \\r\\n \\n \\r This method makes a synchronous HTTP request by default. To make an @@ -62,25 +62,25 @@ class FakeApi(object): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_code_inject____end(callback=callback_function) + >>> thread = api.test_code_inject____end__rn_n_r(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str test_code_inject____end: To test code injection */ ' \" =end + :param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r :return: None If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('callback'): - return self.test_code_inject____end_with_http_info(**kwargs) + return self.test_code_inject____end__rn_n_r_with_http_info(**kwargs) else: - (data) = self.test_code_inject____end_with_http_info(**kwargs) + (data) = self.test_code_inject____end__rn_n_r_with_http_info(**kwargs) return data - def test_code_inject____end_with_http_info(self, **kwargs): + def test_code_inject____end__rn_n_r_with_http_info(self, **kwargs): """ - To test code injection */ ' \" =end + To test code injection */ ' \" =end -- \\r\\n \\n \\r This method makes a synchronous HTTP request by default. To make an @@ -89,17 +89,17 @@ class FakeApi(object): >>> def callback_function(response): >>> pprint(response) >>> - >>> thread = api.test_code_inject____end_with_http_info(callback=callback_function) + >>> thread = api.test_code_inject____end__rn_n_r_with_http_info(callback=callback_function) :param callback function: The callback function for asynchronous request. (optional) - :param str test_code_inject____end: To test code injection */ ' \" =end + :param str test_code_inject____end____rn_n_r: To test code injection */ ' \" =end -- \\r\\n \\n \\r :return: None If the method is called asynchronously, returns the request thread. """ - all_params = ['test_code_inject____end'] + all_params = ['test_code_inject____end____rn_n_r'] all_params.append('callback') all_params.append('_return_http_data_only') @@ -108,11 +108,14 @@ class FakeApi(object): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" - " to method test_code_inject____end" % key + " to method test_code_inject____end__rn_n_r" % key ) params[key] = val del params['kwargs'] + + collection_formats = {} + resource_path = '/fake'.replace('{format}', 'json') path_params = {} @@ -122,20 +125,20 @@ class FakeApi(object): form_params = [] local_var_files = {} - if 'test_code_inject____end' in params: - form_params.append(('test code inject */ ' " =end', params['test_code_inject____end'])) + if 'test_code_inject____end____rn_n_r' in params: + form_params.append(('test code inject */ ' " =end -- \r\n \n \r', params['test_code_inject____end____rn_n_r'])) body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json', '*/ " =end']) + select_header_accept(['application/json', '*/ \" =end -- ']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json', '*/ " =end']) + select_header_content_type(['application/json', '*/ \" =end -- ']) # Authentication setting auth_settings = [] @@ -150,4 +153,5 @@ class FakeApi(object): response_type=None, auth_settings=auth_settings, callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only')) + _return_http_data_only=params.get('_return_http_data_only'), + collection_formats=collection_formats) diff --git a/samples/client/petstore-security-test/python/petstore_api/configuration.py b/samples/client/petstore-security-test/python/petstore_api/configuration.py index 4966e045ba1..b612f103532 100644 --- a/samples/client/petstore-security-test/python/petstore_api/configuration.py +++ b/samples/client/petstore-security-test/python/petstore_api/configuration.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); @@ -23,19 +23,14 @@ """ from __future__ import absolute_import -import base64 -import urllib3 -try: - import httplib -except ImportError: - # for python3 - import http.client as httplib +import urllib3 import sys import logging from six import iteritems +from six.moves import http_client as httplib def singleton(cls, *args, **kw): @@ -61,7 +56,7 @@ class Configuration(object): Constructor """ # Default Base url - self.host = "https://petstore.swagger.io */ ' " =end/v2 */ ' " =end" + self.host = "https://petstore.swagger.io */ ' \" =end -- \\r\\n \\n \\r/v2 */ ' \" =end -- \\r\\n \\n \\r" # Default api client self.api_client = None # Temp file folder for downloading files @@ -225,11 +220,11 @@ class Configuration(object): { 'type': 'api_key', 'in': 'header', - 'key': 'api_key */ ' " =end', - 'value': self.get_api_key_with_prefix('api_key */ ' " =end') + 'key': 'api_key */ ' " =end -- \r\n \n \r', + 'value': self.get_api_key_with_prefix('api_key */ ' " =end -- \r\n \n \r') }, - 'petstore_auth': + 'petstore_auth': { 'type': 'oauth2', 'in': 'header', @@ -248,6 +243,6 @@ class Configuration(object): return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0 */ ' \" =end\n"\ + "Version of the API: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r\n"\ "SDK Package Version: 1.0.0".\ format(env=sys.platform, pyversion=sys.version) diff --git a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py index ef665582431..d5006ee92c6 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py index 2a5591fc2f0..886ec0d5601 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); @@ -51,11 +51,12 @@ class ModelReturn(object): self.__return = _return + @property def _return(self): """ Gets the _return of this ModelReturn. - property description */ ' \" =end + property description */ ' \" =end -- \\r\\n \\n \\r :return: The _return of this ModelReturn. :rtype: int @@ -66,7 +67,7 @@ class ModelReturn(object): def _return(self, _return): """ Sets the _return of this ModelReturn. - property description */ ' \" =end + property description */ ' \" =end -- \\r\\n \\n \\r :param _return: The _return of this ModelReturn. :type: int diff --git a/samples/client/petstore-security-test/python/petstore_api/rest.py b/samples/client/petstore-security-test/python/petstore_api/rest.py index dfb139190d7..fc6b878837c 100644 --- a/samples/client/petstore-security-test/python/petstore_api/rest.py +++ b/samples/client/petstore-security-test/python/petstore_api/rest.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); @@ -24,15 +24,16 @@ from __future__ import absolute_import -import sys import io import json import ssl import certifi import logging +import re # python 2 and python 3 compatibility library -from six import iteritems +from six import PY3 +from six.moves.urllib.parse import urlencode from .configuration import Configuration @@ -41,13 +42,6 @@ try: except ImportError: raise ImportError('Swagger python client requires urllib3.') -try: - # for python3 - from urllib.parse import urlencode -except ImportError: - # for python2 - from urllib import urlencode - logger = logging.getLogger(__name__) @@ -119,7 +113,7 @@ class RESTClientObject(object): :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, - `application/x-www-form-urlencode` + `application/x-www-form-urlencoded` and `multipart/form-data` """ method = method.upper() @@ -141,19 +135,19 @@ class RESTClientObject(object): if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if query_params: url += '?' + urlencode(query_params) - if headers['Content-Type'] == 'application/json': + if re.search('json', headers['Content-Type'], re.IGNORECASE): request_body = None if body: request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, headers=headers) - if headers['Content-Type'] == 'application/x-www-form-urlencoded': + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, headers=headers) - if headers['Content-Type'] == 'multipart/form-data': + elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type # which generated by urllib3 will be overwritten. del headers['Content-Type'] @@ -161,6 +155,19 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) + # Pass a `string` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, str): + request_body = body + r = self.pool_manager.request(method, url, + body=request_body, + headers=headers) + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided arguments. + Please check that your arguments match declared content type.""" + raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: r = self.pool_manager.request(method, url, @@ -174,7 +181,7 @@ class RESTClientObject(object): # In the python 3, the response.data is bytes. # we need to decode it to string. - if sys.version_info > (3,): + if PY3: r.data = r.data.decode('utf8') # log response body diff --git a/samples/client/petstore-security-test/python/setup.py b/samples/client/petstore-security-test/python/setup.py index fa4081f84e6..21f9241b859 100644 --- a/samples/client/petstore-security-test/python/setup.py +++ b/samples/client/petstore-security-test/python/setup.py @@ -1,12 +1,12 @@ # coding: utf-8 """ - Swagger Petstore */ ' \" =end + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - OpenAPI spec version: 1.0.0 */ ' \" =end - Contact: apiteam@swagger.io */ ' \" =end + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); @@ -40,14 +40,15 @@ REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"] setup( name=NAME, version=VERSION, - description="Swagger Petstore */ ' \" =end", - author_email="apiteam@swagger.io */ ' \" =end", + description="Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r", + author_email="apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r", url="", - keywords=["Swagger", "Swagger Petstore */ ' \" =end"], + keywords=["Swagger", "Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r"], install_requires=REQUIRES, packages=find_packages(), include_package_data=True, long_description="""\ - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- """ ) + diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index d478ed45f59..abff48b0bd9 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -51,3 +51,4 @@ setup( This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ """ ) + From 819a8648d5ea944aeb35fefa5e645822ced76528 Mon Sep 17 00:00:00 2001 From: sutdisi Date: Tue, 1 Nov 2016 18:43:29 -0700 Subject: [PATCH 019/269] Jersey2 Patch Support (#4110) * Fix for issue 2848 Adding support for PATH in jersey2 * Updating petstore sample for PATCH update --- .../Java/libraries/jersey2/ApiClient.mustache | 2 + .../petstore/java/jersey2/docs/FakeApi.md | 6 +- .../client/petstore/java/jersey2/gradlew.bat | 180 +++++++++--------- .../java/io/swagger/client/ApiClient.java | 3 + .../io/swagger/client/RFC3339DateFormat.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 5 +- .../model/AdditionalPropertiesClass.java | 5 +- .../java/io/swagger/client/model/Animal.java | 5 +- .../io/swagger/client/model/AnimalFarm.java | 5 +- .../model/ArrayOfArrayOfNumberOnly.java | 5 +- .../client/model/ArrayOfNumberOnly.java | 5 +- .../io/swagger/client/model/ArrayTest.java | 5 +- .../java/io/swagger/client/model/Cat.java | 5 +- .../io/swagger/client/model/Category.java | 5 +- .../java/io/swagger/client/model/Client.java | 5 +- .../java/io/swagger/client/model/Dog.java | 5 +- .../io/swagger/client/model/EnumArrays.java | 5 +- .../io/swagger/client/model/EnumClass.java | 1 - .../io/swagger/client/model/EnumTest.java | 5 +- .../io/swagger/client/model/FormatTest.java | 5 +- .../swagger/client/model/HasOnlyReadOnly.java | 5 +- .../java/io/swagger/client/model/MapTest.java | 5 +- ...ropertiesAndAdditionalPropertiesClass.java | 5 +- .../client/model/Model200Response.java | 5 +- .../client/model/ModelApiResponse.java | 5 +- .../io/swagger/client/model/ModelReturn.java | 5 +- .../java/io/swagger/client/model/Name.java | 5 +- .../io/swagger/client/model/NumberOnly.java | 5 +- .../java/io/swagger/client/model/Order.java | 5 +- .../java/io/swagger/client/model/Pet.java | 5 +- .../swagger/client/model/ReadOnlyFirst.java | 5 +- .../client/model/SpecialModelName.java | 5 +- .../java/io/swagger/client/model/Tag.java | 5 +- .../java/io/swagger/client/model/User.java | 5 +- 34 files changed, 185 insertions(+), 149 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 4ea86f5cd6f..668b34a90ae 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -635,6 +635,8 @@ public class ApiClient { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity); } else { throw new ApiException(500, "unknown method type " + method); } diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 9012aff618e..29813bd9349 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -54,7 +54,7 @@ No authorization required # **testEndpointParameters** -> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password) +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -90,8 +90,9 @@ byte[] binary = B; // byte[] | None LocalDate date = new LocalDate(); // LocalDate | None DateTime dateTime = new DateTime(); // DateTime | None String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None try { - apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password); + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); } catch (ApiException e) { System.err.println("Exception when calling FakeApi#testEndpointParameters"); e.printStackTrace(); @@ -115,6 +116,7 @@ Name | Type | Description | Notes **date** | **LocalDate**| None | [optional] **dateTime** | **DateTime**| None | [optional] **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey2/gradlew.bat b/samples/client/petstore/java/jersey2/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/jersey2/gradlew.bat +++ b/samples/client/petstore/java/jersey2/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index ec4fea20fad..5eb7e89e13e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -22,6 +22,7 @@ import org.glassfish.jersey.media.multipart.MultiPartFeature; import java.io.IOException; import java.io.InputStream; + import java.nio.file.Files; import java.util.Collection; import java.util.Collections; @@ -623,6 +624,8 @@ public class ApiClient { response = invocationBuilder.put(entity); } else if ("DELETE".equals(method)) { response = invocationBuilder.delete(); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.header("X-HTTP-Method-Override", "PATCH").post(entity); } else { throw new ApiException(500, "unknown method type " + method); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java index 3d287008be5..d662f9457d7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index 70d8b276c1c..9c08693ef37 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -94,9 +94,10 @@ public class FakeApi { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @throws ApiException if fails to make API call */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password) throws ApiException { + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { Object localVarPostBody = null; // verify the required parameter 'number' is set @@ -155,6 +156,8 @@ if (dateTime != null) localVarFormParams.put("dateTime", dateTime); if (password != null) localVarFormParams.put("password", password); +if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); final String[] localVarAccepts = { "application/xml; charset=utf-8", "application/json; charset=utf-8" diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 2da13804a0d..21e4efaeaa2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -34,12 +34,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @JsonProperty("map_property") private Map mapProperty = new HashMap(); @@ -111,6 +110,7 @@ public class AdditionalPropertiesClass { return Objects.hash(mapProperty, mapOfMapProperty); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -132,5 +132,6 @@ public class AdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 346da224ad1..993f9bbe6f4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @JsonProperty("className") private String className = null; @@ -98,6 +97,7 @@ public class Animal { return Objects.hash(className, color); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..181812be4f4 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import io.swagger.client.model.Animal; import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -53,6 +52,7 @@ public class AnimalFarm extends ArrayList { return Objects.hash(super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -72,5 +72,6 @@ public class AnimalFarm extends ArrayList { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index a99f2009385..c02b8e1a37f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -84,6 +83,7 @@ public class ArrayOfArrayOfNumberOnly { return Objects.hash(arrayArrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -104,5 +104,6 @@ public class ArrayOfArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 1aaf27b9921..fe97b65e190 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -84,6 +83,7 @@ public class ArrayOfNumberOnly { return Objects.hash(arrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -104,5 +104,6 @@ public class ArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java index 124d8bfa3a1..a035e8fe2f0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ArrayTest.java @@ -34,12 +34,11 @@ import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); @@ -138,6 +137,7 @@ public class ArrayTest { return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -160,5 +160,6 @@ public class ArrayTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java index 41dc312a10f..b2532f78f85 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Cat.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @JsonProperty("declawed") private Boolean declawed = null; @@ -78,6 +77,7 @@ public class Cat extends Animal { return Objects.hash(declawed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -98,5 +98,6 @@ public class Cat extends Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index ba4ce89c297..84def6a8dac 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @JsonProperty("id") private Long id = null; @@ -98,6 +97,7 @@ public class Category { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Category { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java index 43ade4b6fcb..1540bc4d7de 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Client.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @JsonProperty("client") private String client = null; @@ -76,6 +75,7 @@ public class Client { return Objects.hash(client); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,5 +96,6 @@ public class Client { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java index 788aee5c226..d5e9063c988 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Dog.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @JsonProperty("breed") private String breed = null; @@ -78,6 +77,7 @@ public class Dog extends Animal { return Objects.hash(breed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -98,5 +98,6 @@ public class Dog extends Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java index 45295c524f6..d8be37b302c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumArrays.java @@ -33,12 +33,11 @@ import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -165,6 +164,7 @@ public class EnumArrays { return Objects.hash(justSymbol, arrayEnum); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -186,5 +186,6 @@ public class EnumArrays { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java index f9887c69340..c2f4ae53735 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumClass.java @@ -27,7 +27,6 @@ package io.swagger.client.model; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index a7268316c40..cf3cab66458 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -210,6 +209,7 @@ public class EnumTest { return Objects.hash(enumString, enumInteger, enumNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -232,5 +232,6 @@ public class EnumTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index 2b5b4204281..df839b0898c 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @JsonProperty("integer") private Integer integer = null; @@ -353,6 +352,7 @@ public class FormatTest { return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -385,5 +385,6 @@ public class FormatTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d874a545244..9f59c6a47bd 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @JsonProperty("bar") private String bar = null; @@ -80,6 +79,7 @@ public class HasOnlyReadOnly { return Objects.hash(bar, foo); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -101,5 +101,6 @@ public class HasOnlyReadOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java index f8cf1ad5d1a..335dcb31cbf 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MapTest.java @@ -34,12 +34,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -141,6 +140,7 @@ public class MapTest { return Objects.hash(mapMapOfString, mapOfEnumString); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -162,5 +162,6 @@ public class MapTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 20958fd50d8..af5292584ab 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -36,12 +36,11 @@ import java.util.List; import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") private String uuid = null; @@ -130,6 +129,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { return Objects.hash(uuid, dateTime, map); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -152,5 +152,6 @@ public class MixedPropertiesAndAdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java index 8f48dd8020e..e905b7f9183 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Model200Response.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @JsonProperty("name") private Integer name = null; @@ -99,6 +98,7 @@ public class Model200Response { return Objects.hash(name, propertyClass); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -120,5 +120,6 @@ public class Model200Response { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java index 70ee2a834c0..f554939b898 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @JsonProperty("code") private Integer code = null; @@ -120,6 +119,7 @@ public class ModelApiResponse { return Objects.hash(code, type, message); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -142,5 +142,6 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java index 28294a15090..5332ff4fe2b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ModelReturn.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @JsonProperty("return") private Integer _return = null; @@ -77,6 +76,7 @@ public class ModelReturn { return Objects.hash(_return); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -97,5 +97,6 @@ public class ModelReturn { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java index 4b70e8df1a6..d26b62921fa 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Name.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @JsonProperty("name") private Integer name = null; @@ -125,6 +124,7 @@ public class Name { return Objects.hash(name, snakeCase, property, _123Number); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -148,5 +148,6 @@ public class Name { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java index ad74058d2e5..3dc6009047f 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/NumberOnly.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @JsonProperty("JustNumber") private BigDecimal justNumber = null; @@ -77,6 +76,7 @@ public class NumberOnly { return Objects.hash(justNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -97,5 +97,6 @@ public class NumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 1616b030b9d..4eea9879c86 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @JsonProperty("id") private Long id = null; @@ -219,6 +218,7 @@ public class Order { return Objects.hash(id, petId, quantity, shipDate, status, complete); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -244,5 +244,6 @@ public class Order { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index a89e0ea3e05..3ef257006ec 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -35,12 +35,11 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @JsonProperty("id") private Long id = null; @@ -232,6 +231,7 @@ public class Pet { return Objects.hash(id, category, name, photoUrls, tags, status); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -257,5 +257,6 @@ public class Pet { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 63e11bf14fd..0cbe504a297 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @JsonProperty("bar") private String bar = null; @@ -89,6 +88,7 @@ public class ReadOnlyFirst { return Objects.hash(bar, baz); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -110,5 +110,6 @@ public class ReadOnlyFirst { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java index f8c5c06ca40..96bbd285945 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @JsonProperty("$special[property.name]") private Long specialPropertyName = null; @@ -76,6 +75,7 @@ public class SpecialModelName { return Objects.hash(specialPropertyName); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,5 +96,6 @@ public class SpecialModelName { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 27be94678da..330d2c8faa1 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @JsonProperty("id") private Long id = null; @@ -98,6 +97,7 @@ public class Tag { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Tag { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 84e3b147049..97fc77b476d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @JsonProperty("id") private Long id = null; @@ -230,6 +229,7 @@ public class User { return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -257,5 +257,6 @@ public class User { } return o.toString().replace("\n", "\n "); } + } From 5c0ce022e908f7433bee2d1cb5795acb3eaecbea Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 2 Nov 2016 11:17:04 +0800 Subject: [PATCH 020/269] update dart intl version --- .../swagger-codegen/src/main/resources/dart/pubspec.mustache | 2 +- samples/client/petstore/dart/swagger/pubspec.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache index 1167498909e..ce0a309ea82 100644 --- a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache @@ -4,7 +4,7 @@ description: {{pubDescription}} dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - intl: "^0.12.4+2" + intl: ">=0.12.4" dev_dependencies: guinness: '^0.1.17' diff --git a/samples/client/petstore/dart/swagger/pubspec.yaml b/samples/client/petstore/dart/swagger/pubspec.yaml index e74546ea210..8ad53b9d6e6 100644 --- a/samples/client/petstore/dart/swagger/pubspec.yaml +++ b/samples/client/petstore/dart/swagger/pubspec.yaml @@ -4,7 +4,7 @@ description: Swagger API client dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - intl: "^0.12.4+2" + intl: ">=0.12.4" dev_dependencies: guinness: '^0.1.17' From 4eb75f808896ff835ffb7c763371dc36ad1c7a5e Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 2 Nov 2016 15:40:00 +0800 Subject: [PATCH 021/269] add back setter to spring model (readonly attr) --- .../main/resources/JavaSpring/pojo.mustache | 4 ---- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/model/HasOnlyReadOnly.java | 18 ++++++++++++++++++ .../src/main/java/io/swagger/model/Name.java | 18 ++++++++++++++++++ .../java/io/swagger/model/ReadOnlyFirst.java | 9 +++++++++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../java/io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../java/io/swagger/model/HasOnlyReadOnly.java | 18 ++++++++++++++++++ .../src/main/java/io/swagger/model/Name.java | 18 ++++++++++++++++++ .../java/io/swagger/model/ReadOnlyFirst.java | 9 +++++++++ .../src/main/java/io/swagger/api/FakeApi.java | 2 +- .../java/io/swagger/api/FakeApiController.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../java/io/swagger/api/PetApiController.java | 2 +- .../java/io/swagger/model/HasOnlyReadOnly.java | 18 ++++++++++++++++++ .../src/main/java/io/swagger/model/Name.java | 18 ++++++++++++++++++ .../java/io/swagger/model/ReadOnlyFirst.java | 9 +++++++++ 22 files changed, 147 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache index 6e5c1b74115..06c8e3048a0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache @@ -27,7 +27,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/vars}} {{#vars}} - {{^isReadOnly}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; return this; @@ -47,7 +46,6 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali } {{/isMapContainer}} - {{/isReadOnly}} /** {{#description}} * {{{description}}} @@ -70,12 +68,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } - {{^isReadOnly}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; } - {{/isReadOnly}} {{/vars}} diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 812ca04e270..dbdffde69ce 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java index 04c4ed27aa3..abe1992830a 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 50f6497e2f1..835b83c6234 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Client; -import java.time.OffsetDateTime; import java.time.LocalDate; +import java.time.OffsetDateTime; import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index 6a8018d2c21..d87e7a68b65 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 3f5492a2e62..55817f8dd14 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -17,6 +17,11 @@ public class HasOnlyReadOnly { @JsonProperty("foo") private String foo = null; + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,15 @@ public class HasOnlyReadOnly { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + /** * Get foo * @return foo @@ -35,6 +49,10 @@ public class HasOnlyReadOnly { return foo; } + public void setFoo(String foo) { + this.foo = foo; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java index 09085fb52dc..aa31ac8d79a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java @@ -42,6 +42,11 @@ public class Name { this.name = name; } + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + /** * Get snakeCase * @return snakeCase @@ -51,6 +56,10 @@ public class Name { return snakeCase; } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + public Name property(String property) { this.property = property; return this; @@ -69,6 +78,11 @@ public class Name { this.property = property; } + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + /** * Get _123Number * @return _123Number @@ -78,6 +92,10 @@ public class Name { return _123Number; } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java index 50a2a7e4184..76d529c087a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -17,6 +17,11 @@ public class ReadOnlyFirst { @JsonProperty("baz") private String baz = null; + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,10 @@ public class ReadOnlyFirst { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index 8fe8f34bb31..24e32cf2341 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ package io.swagger.api; import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index f4adae4ec88..dcae4cacdc7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ package io.swagger.api; import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 5b69114555e..3af82092a60 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index 695d4cc2386..75de52391ac 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 3f5492a2e62..55817f8dd14 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -17,6 +17,11 @@ public class HasOnlyReadOnly { @JsonProperty("foo") private String foo = null; + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,15 @@ public class HasOnlyReadOnly { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + /** * Get foo * @return foo @@ -35,6 +49,10 @@ public class HasOnlyReadOnly { return foo; } + public void setFoo(String foo) { + this.foo = foo; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java index 09085fb52dc..aa31ac8d79a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java @@ -42,6 +42,11 @@ public class Name { this.name = name; } + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + /** * Get snakeCase * @return snakeCase @@ -51,6 +56,10 @@ public class Name { return snakeCase; } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + public Name property(String property) { this.property = property; return this; @@ -69,6 +78,11 @@ public class Name { this.property = property; } + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + /** * Get _123Number * @return _123Number @@ -78,6 +92,10 @@ public class Name { return _123Number; } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java index 50a2a7e4184..76d529c087a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -17,6 +17,11 @@ public class ReadOnlyFirst { @JsonProperty("baz") private String baz = null; + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,10 @@ public class ReadOnlyFirst { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index 8fe8f34bb31..24e32cf2341 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -2,8 +2,8 @@ package io.swagger.api; import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index f4adae4ec88..dcae4cacdc7 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -2,8 +2,8 @@ package io.swagger.api; import io.swagger.model.Client; import org.joda.time.LocalDate; -import java.math.BigDecimal; import org.joda.time.DateTime; +import java.math.BigDecimal; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 5b69114555e..3af82092a60 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index 695d4cc2386..75de52391ac 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 3f5492a2e62..55817f8dd14 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -17,6 +17,11 @@ public class HasOnlyReadOnly { @JsonProperty("foo") private String foo = null; + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,15 @@ public class HasOnlyReadOnly { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + /** * Get foo * @return foo @@ -35,6 +49,10 @@ public class HasOnlyReadOnly { return foo; } + public void setFoo(String foo) { + this.foo = foo; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java index 09085fb52dc..aa31ac8d79a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java @@ -42,6 +42,11 @@ public class Name { this.name = name; } + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + /** * Get snakeCase * @return snakeCase @@ -51,6 +56,10 @@ public class Name { return snakeCase; } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + public Name property(String property) { this.property = property; return this; @@ -69,6 +78,11 @@ public class Name { this.property = property; } + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + /** * Get _123Number * @return _123Number @@ -78,6 +92,10 @@ public class Name { return _123Number; } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + @Override public boolean equals(java.lang.Object o) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java index 50a2a7e4184..76d529c087a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -17,6 +17,11 @@ public class ReadOnlyFirst { @JsonProperty("baz") private String baz = null; + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + /** * Get bar * @return bar @@ -26,6 +31,10 @@ public class ReadOnlyFirst { return bar; } + public void setBar(String bar) { + this.bar = bar; + } + public ReadOnlyFirst baz(String baz) { this.baz = baz; return this; From 8fb33980dc0d3c0915c5f8d93e1d7ee47f2b3980 Mon Sep 17 00:00:00 2001 From: Simon Morris Date: Wed, 2 Nov 2016 06:35:01 -0700 Subject: [PATCH 022/269] Nancy fx work (#4107) * Added switch to config to toggle use of yaml base path as module paths * NancyFX template updated to return collections as array to allow framework to find views by type name for text/html mime type * Added some more parser fixes for NancyFX * Refactored collection parsers in Parameters.cs and changed some to return nullable collections to match the parameter mappings in AbstractCSharpCodegen * re-ran petstore build --- .../src/main/resources/nancyfx/api.mustache | 2 +- .../resources/nancyfx/parameters.mustache | 175 ++++++++++-------- .../server/petstore/nancyfx/IO.Swagger.sln | 19 +- .../nancyfx/src/IO.Swagger/IO.Swagger.csproj | 3 +- .../src/IO.Swagger/Modules/PetModule.cs | 4 +- .../src/IO.Swagger/Utils/Parameters.cs | 175 ++++++++++-------- 6 files changed, 215 insertions(+), 163 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index 1e66c83c769..b4213ff2056 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -30,7 +30,7 @@ namespace {{packageName}}.{{packageContext}}.Modules {{/hasMore}}{{/isBodyParam}}{{/allParams}}{{#allParams}}{{#required}} Preconditions.IsNotNull({{paramName}}, "Required parameter: '{{paramName}}' is missing at '{{operationId}}'"); {{/required}}{{/allParams}} - {{#returnType}}return {{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{^returnType}} + {{#returnType}}return {{/returnType}}service.{{operationId}}(Context{{#allParams.0}}, {{/allParams.0}}{{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}}{{#isListContainer}}.ToArray(){{/isListContainer}}{{/returnType}};{{^returnType}} return new Response { ContentType = "{{produces.0.mediaType}}"};{{/returnType}} }; {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache index e55a82416ec..75486f59f46 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/parameters.mustache @@ -166,19 +166,19 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); - parsers.Put(typeof(IEnumerable), value => value); - parsers.Put(typeof(ICollection), value => value); - parsers.Put(typeof(IList), value => value); - parsers.Put(typeof(List), value => value); - parsers.Put(typeof(ISet), value => value); - parsers.Put(typeof(HashSet), value => value); + parsers.Put(typeof(IEnumerable), ImmutableListParse(value => value)); + parsers.Put(typeof(ICollection), ImmutableListParse(value => value)); + parsers.Put(typeof(IList), ImmutableListParse(value => value)); + parsers.Put(typeof(List), ListParse(value => value)); + parsers.Put(typeof(ISet), ImmutableListParse(value => value)); + parsers.Put(typeof(HashSet), SetParse(value => value)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(List), ListParse(bool.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(bool.Parse)); - parsers.Put(typeof(HashSet), SetParse(bool.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(List), NullableListParse(bool.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(bool.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(bool.Parse)); parsers.Put(typeof(IEnumerable), ImmutableListParse(byte.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(byte.Parse)); @@ -186,6 +186,7 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(List), ListParse(byte.Parse)); parsers.Put(typeof(ISet), ImmutableSetParse(byte.Parse)); parsers.Put(typeof(HashSet), SetParse(byte.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(sbyte.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(sbyte.Parse)); parsers.Put(typeof(IList), ImmutableListParse(sbyte.Parse)); @@ -199,6 +200,7 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(List), ListParse(short.Parse)); parsers.Put(typeof(ISet), ImmutableSetParse(short.Parse)); parsers.Put(typeof(HashSet), SetParse(short.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(ushort.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(ushort.Parse)); parsers.Put(typeof(IList), ImmutableListParse(ushort.Parse)); @@ -206,12 +208,13 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(ISet), ImmutableSetParse(ushort.Parse)); parsers.Put(typeof(HashSet), SetParse(ushort.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(int.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(int.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(int.Parse)); - parsers.Put(typeof(List), ListParse(int.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(int.Parse)); - parsers.Put(typeof(HashSet), SetParse(int.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(List), NullableListParse(int.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(int.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(int.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(uint.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(uint.Parse)); parsers.Put(typeof(IList), ImmutableListParse(uint.Parse)); @@ -219,12 +222,13 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(ISet), ImmutableSetParse(uint.Parse)); parsers.Put(typeof(HashSet), SetParse(uint.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(long.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(long.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(long.Parse)); - parsers.Put(typeof(List), ListParse(long.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(long.Parse)); - parsers.Put(typeof(HashSet), SetParse(long.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(List), NullableListParse(long.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(long.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(long.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(ulong.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(ulong.Parse)); parsers.Put(typeof(IList), ImmutableListParse(ulong.Parse)); @@ -232,34 +236,33 @@ namespace {{packageName}}.{{packageContext}}.Utils parsers.Put(typeof(ISet), ImmutableSetParse(ulong.Parse)); parsers.Put(typeof(HashSet), SetParse(ulong.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(float.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(float.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(float.Parse)); - parsers.Put(typeof(List), ListParse(float.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(float.Parse)); - parsers.Put(typeof(HashSet), SetParse(float.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(List), NullableListParse(float.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(float.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(float.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(double.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(double.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(double.Parse)); - parsers.Put(typeof(List), ListParse(double.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(double.Parse)); - parsers.Put(typeof(HashSet), SetParse(double.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(List), NullableListParse(double.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(double.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(double.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(List), ListParse(decimal.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(decimal.Parse)); - parsers.Put(typeof(HashSet), SetParse(decimal.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(List), NullableListParse(decimal.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(decimal.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(decimal.Parse)); - - parsers.Put(typeof(IEnumerable), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(List), ListParse(DateTime.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(DateTime.Parse)); - parsers.Put(typeof(HashSet), SetParse(DateTime.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(List), NullableListParse(DateTime.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(DateTime.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(DateTime.Parse)); parsers.Put(typeof(IEnumerable), ImmutableListParse(TimeSpan.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(TimeSpan.Parse)); @@ -295,6 +298,11 @@ namespace {{packageName}}.{{packageContext}}.Utils }; } + private static Func NullableListParse(Func itemParser) where T: struct + { + return ListParse(it => it.ToNullable(itemParser)); + } + private static Func ListParse(Func itemParser) { return parameter => @@ -303,15 +311,15 @@ namespace {{packageName}}.{{packageContext}}.Utils { return new List(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToList(); - return results; + return ParseCollection(parameter.Value, itemParser).ToList(); }; } + private static Func NullableImmutableListParse(Func itemParser) where T: struct + { + return ImmutableListParse(it => it.ToNullable(itemParser)); + } + private static Func ImmutableListParse(Func itemParser) { return parameter => @@ -320,15 +328,15 @@ namespace {{packageName}}.{{packageContext}}.Utils { return Lists.EmptyList(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToImmutableList(); - return results; + return ParseCollection(parameter.Value, itemParser).ToImmutableList(); }; } + private static Func NullableSetParse(Func itemParser) where T: struct + { + return SetParse(it => it.ToNullable(itemParser)); + } + private static Func SetParse(Func itemParser) { return parameter => @@ -337,15 +345,15 @@ namespace {{packageName}}.{{packageContext}}.Utils { return new HashSet(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToSet(); - return results; + return ParseCollection(parameter.Value, itemParser).ToSet(); }; } + private static Func NullableImmutableSetParse(Func itemParser) where T: struct + { + return ImmutableSetParse(it => it.ToNullable(itemParser)); + } + private static Func ImmutableSetParse(Func itemParser) { return parameter => @@ -354,12 +362,7 @@ namespace {{packageName}}.{{packageContext}}.Utils { return Sets.EmptySet(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToImmutableHashSet(); - return results; + return ParseCollection(parameter.Value, itemParser).ToImmutableHashSet(); }; } @@ -386,6 +389,32 @@ namespace {{packageName}}.{{packageContext}}.Utils parameter.Name, parameter.Value, type)); } + private static IEnumerable ParseCollection(string value, Func itemParser) + { + var results = value.Split(new[] { ',' }, StringSplitOptions.None) + .Where(it => it != null) + .Select(it => it.Trim()) + .Select(itemParser); + return results; + } + + public static T? ToNullable(this string s, Func itemParser) where T : struct + { + T? result = new T?(); + try + { + if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) + { + result = itemParser(s); + } + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse value: '{0}' to nullable: '{1}'", s, typeof(T).ToString()), e); + } + return result; + } + private class Parameter { internal string Name { get; private set; } diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index e6fd22af6f6..09301395de7 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{7D50D142-14E1-4E99-842B-18D3AF159948}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{3B55ED13-A471-44B1-A8D5-C158723C0A0C}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,17 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -<<<<<<< HEAD -{7D50D142-14E1-4E99-842B-18D3AF159948}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{7D50D142-14E1-4E99-842B-18D3AF159948}.Debug|Any CPU.Build.0 = Debug|Any CPU -{7D50D142-14E1-4E99-842B-18D3AF159948}.Release|Any CPU.ActiveCfg = Release|Any CPU -{7D50D142-14E1-4E99-842B-18D3AF159948}.Release|Any CPU.Build.0 = Release|Any CPU -======= -{1CE943E7-586D-4D9C-BE8B-3E005FDC39D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{1CE943E7-586D-4D9C-BE8B-3E005FDC39D1}.Debug|Any CPU.Build.0 = Debug|Any CPU -{1CE943E7-586D-4D9C-BE8B-3E005FDC39D1}.Release|Any CPU.ActiveCfg = Release|Any CPU -{1CE943E7-586D-4D9C-BE8B-3E005FDC39D1}.Release|Any CPU.Build.0 = Release|Any CPU ->>>>>>> 92c474b2c235f4635e4be43a97c7941fec64dc82 +{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -29,4 +22,4 @@ EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection -EndGlobal +EndGlobal \ No newline at end of file diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index 60535f7aae6..a103786b912 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {7D50D142-14E1-4E99-842B-18D3AF159948} + {3B55ED13-A471-44B1-A8D5-C158723C0A0C} Library Properties IO.Swagger.v2 @@ -63,3 +63,4 @@ + diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs index d6922531e24..edfa0ecac4a 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Modules/PetModule.cs @@ -55,7 +55,7 @@ namespace IO.Swagger.v2.Modules var status = Parameters.ValueOf(parameters, Context.Request, "status", ParameterType.Query); Preconditions.IsNotNull(status, "Required parameter: 'status' is missing at 'FindPetsByStatus'"); - return service.FindPetsByStatus(Context, status); + return service.FindPetsByStatus(Context, status).ToArray(); }; Get["/pet/findByTags"] = parameters => @@ -63,7 +63,7 @@ namespace IO.Swagger.v2.Modules var tags = Parameters.ValueOf>(parameters, Context.Request, "tags", ParameterType.Query); Preconditions.IsNotNull(tags, "Required parameter: 'tags' is missing at 'FindPetsByTags'"); - return service.FindPetsByTags(Context, tags); + return service.FindPetsByTags(Context, tags).ToArray(); }; Get["/pet/{petId}"] = parameters => diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs index 7f0e848f98a..6175758fd9a 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/Utils/Parameters.cs @@ -166,19 +166,19 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(LocalTime), SafeParse(ParseLocalTime)); parsers.Put(typeof(LocalTime?), SafeParse(ParseLocalTime)); - parsers.Put(typeof(IEnumerable), value => value); - parsers.Put(typeof(ICollection), value => value); - parsers.Put(typeof(IList), value => value); - parsers.Put(typeof(List), value => value); - parsers.Put(typeof(ISet), value => value); - parsers.Put(typeof(HashSet), value => value); + parsers.Put(typeof(IEnumerable), ImmutableListParse(value => value)); + parsers.Put(typeof(ICollection), ImmutableListParse(value => value)); + parsers.Put(typeof(IList), ImmutableListParse(value => value)); + parsers.Put(typeof(List), ListParse(value => value)); + parsers.Put(typeof(ISet), ImmutableListParse(value => value)); + parsers.Put(typeof(HashSet), SetParse(value => value)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(bool.Parse)); - parsers.Put(typeof(List), ListParse(bool.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(bool.Parse)); - parsers.Put(typeof(HashSet), SetParse(bool.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(bool.Parse)); + parsers.Put(typeof(List), NullableListParse(bool.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(bool.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(bool.Parse)); parsers.Put(typeof(IEnumerable), ImmutableListParse(byte.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(byte.Parse)); @@ -186,6 +186,7 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(List), ListParse(byte.Parse)); parsers.Put(typeof(ISet), ImmutableSetParse(byte.Parse)); parsers.Put(typeof(HashSet), SetParse(byte.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(sbyte.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(sbyte.Parse)); parsers.Put(typeof(IList), ImmutableListParse(sbyte.Parse)); @@ -199,6 +200,7 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(List), ListParse(short.Parse)); parsers.Put(typeof(ISet), ImmutableSetParse(short.Parse)); parsers.Put(typeof(HashSet), SetParse(short.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(ushort.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(ushort.Parse)); parsers.Put(typeof(IList), ImmutableListParse(ushort.Parse)); @@ -206,12 +208,13 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(ISet), ImmutableSetParse(ushort.Parse)); parsers.Put(typeof(HashSet), SetParse(ushort.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(int.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(int.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(int.Parse)); - parsers.Put(typeof(List), ListParse(int.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(int.Parse)); - parsers.Put(typeof(HashSet), SetParse(int.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(int.Parse)); + parsers.Put(typeof(List), NullableListParse(int.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(int.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(int.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(uint.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(uint.Parse)); parsers.Put(typeof(IList), ImmutableListParse(uint.Parse)); @@ -219,12 +222,13 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(ISet), ImmutableSetParse(uint.Parse)); parsers.Put(typeof(HashSet), SetParse(uint.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(long.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(long.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(long.Parse)); - parsers.Put(typeof(List), ListParse(long.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(long.Parse)); - parsers.Put(typeof(HashSet), SetParse(long.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(long.Parse)); + parsers.Put(typeof(List), NullableListParse(long.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(long.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(long.Parse)); + parsers.Put(typeof(IEnumerable), ImmutableListParse(ulong.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(ulong.Parse)); parsers.Put(typeof(IList), ImmutableListParse(ulong.Parse)); @@ -232,34 +236,33 @@ namespace IO.Swagger.v2.Utils parsers.Put(typeof(ISet), ImmutableSetParse(ulong.Parse)); parsers.Put(typeof(HashSet), SetParse(ulong.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(float.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(float.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(float.Parse)); - parsers.Put(typeof(List), ListParse(float.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(float.Parse)); - parsers.Put(typeof(HashSet), SetParse(float.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(float.Parse)); + parsers.Put(typeof(List), NullableListParse(float.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(float.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(float.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(double.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(double.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(double.Parse)); - parsers.Put(typeof(List), ListParse(double.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(double.Parse)); - parsers.Put(typeof(HashSet), SetParse(double.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(double.Parse)); + parsers.Put(typeof(List), NullableListParse(double.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(double.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(double.Parse)); - parsers.Put(typeof(IEnumerable), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(decimal.Parse)); - parsers.Put(typeof(List), ListParse(decimal.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(decimal.Parse)); - parsers.Put(typeof(HashSet), SetParse(decimal.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(decimal.Parse)); + parsers.Put(typeof(List), NullableListParse(decimal.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(decimal.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(decimal.Parse)); - - parsers.Put(typeof(IEnumerable), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(ICollection), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(IList), ImmutableListParse(DateTime.Parse)); - parsers.Put(typeof(List), ListParse(DateTime.Parse)); - parsers.Put(typeof(ISet), ImmutableSetParse(DateTime.Parse)); - parsers.Put(typeof(HashSet), SetParse(DateTime.Parse)); + parsers.Put(typeof(IEnumerable), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(ICollection), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(IList), NullableImmutableListParse(DateTime.Parse)); + parsers.Put(typeof(List), NullableListParse(DateTime.Parse)); + parsers.Put(typeof(ISet), NullableImmutableSetParse(DateTime.Parse)); + parsers.Put(typeof(HashSet), NullableSetParse(DateTime.Parse)); parsers.Put(typeof(IEnumerable), ImmutableListParse(TimeSpan.Parse)); parsers.Put(typeof(ICollection), ImmutableListParse(TimeSpan.Parse)); @@ -295,6 +298,11 @@ namespace IO.Swagger.v2.Utils }; } + private static Func NullableListParse(Func itemParser) where T: struct + { + return ListParse(it => it.ToNullable(itemParser)); + } + private static Func ListParse(Func itemParser) { return parameter => @@ -303,15 +311,15 @@ namespace IO.Swagger.v2.Utils { return new List(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToList(); - return results; + return ParseCollection(parameter.Value, itemParser).ToList(); }; } + private static Func NullableImmutableListParse(Func itemParser) where T: struct + { + return ImmutableListParse(it => it.ToNullable(itemParser)); + } + private static Func ImmutableListParse(Func itemParser) { return parameter => @@ -320,15 +328,15 @@ namespace IO.Swagger.v2.Utils { return Lists.EmptyList(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToImmutableList(); - return results; + return ParseCollection(parameter.Value, itemParser).ToImmutableList(); }; } + private static Func NullableSetParse(Func itemParser) where T: struct + { + return SetParse(it => it.ToNullable(itemParser)); + } + private static Func SetParse(Func itemParser) { return parameter => @@ -337,15 +345,15 @@ namespace IO.Swagger.v2.Utils { return new HashSet(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToSet(); - return results; + return ParseCollection(parameter.Value, itemParser).ToSet(); }; } + private static Func NullableImmutableSetParse(Func itemParser) where T: struct + { + return ImmutableSetParse(it => it.ToNullable(itemParser)); + } + private static Func ImmutableSetParse(Func itemParser) { return parameter => @@ -354,12 +362,7 @@ namespace IO.Swagger.v2.Utils { return Sets.EmptySet(); } - var results = parameter.Value.Split(new[] { ',' }, StringSplitOptions.None) - .Where(it => it != null) - .Select(it => it.Trim()) - .Select(itemParser) - .ToImmutableHashSet(); - return results; + return ParseCollection(parameter.Value, itemParser).ToImmutableHashSet(); }; } @@ -386,6 +389,32 @@ namespace IO.Swagger.v2.Utils parameter.Name, parameter.Value, type)); } + private static IEnumerable ParseCollection(string value, Func itemParser) + { + var results = value.Split(new[] { ',' }, StringSplitOptions.None) + .Where(it => it != null) + .Select(it => it.Trim()) + .Select(itemParser); + return results; + } + + public static T? ToNullable(this string s, Func itemParser) where T : struct + { + T? result = new T?(); + try + { + if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0) + { + result = itemParser(s); + } + } + catch (Exception e) + { + throw new InvalidOperationException(Strings.Format("Unable to parse value: '{0}' to nullable: '{1}'", s, typeof(T).ToString()), e); + } + return result; + } + private class Parameter { internal string Name { get; private set; } From 8eefe863bfbeb43c1306317a148a6b7d49e65229 Mon Sep 17 00:00:00 2001 From: wwn Date: Wed, 2 Nov 2016 18:45:25 +0100 Subject: [PATCH 023/269] Added isEmtyString check to avoid IndexOutOfBoundException --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 3eba155581b..23bfb825bea 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2947,7 +2947,7 @@ public class DefaultCodegen { m = p.matcher(word); } - if (lowercaseFirstLetter) { + if (lowercaseFirstLetter && word.length() > 0) { word = word.substring(0, 1).toLowerCase() + word.substring(1); } From 088ba979672729e14b8d8b888a578e2383732c2a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 2 Nov 2016 16:55:22 -0400 Subject: [PATCH 024/269] updated to next development version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index bb277a2a6bf..14183730254 100644 --- a/pom.xml +++ b/pom.xml @@ -807,7 +807,7 @@ - 1.0.23 + 1.0.24-SNAPSHOT 2.11.1 2.3.4 1.5.10 From 60c7d90d229ee2657bfee9e634cf0622e18a443a Mon Sep 17 00:00:00 2001 From: sanjeewa-malalgoda Date: Thu, 3 Nov 2016 10:39:52 +0530 Subject: [PATCH 025/269] remove glassfish dependencies and use MSF4J internal implementation for the simplicity and reduce dependencies --- .../src/main/resources/MSF4J/api.mustache | 4 ++-- .../src/main/resources/MSF4J/apiService.mustache | 3 ++- .../src/main/resources/MSF4J/apiServiceImpl.mustache | 3 ++- .../src/main/resources/MSF4J/formParams.mustache | 2 +- .../src/main/resources/MSF4J/pom.mustache | 10 ---------- .../main/resources/MSF4J/serviceFormParams.mustache | 2 +- 6 files changed, 8 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/api.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/api.mustache index f90d2564187..8a04d1cad7e 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/api.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/api.mustache @@ -15,8 +15,8 @@ import {{package}}.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/apiService.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/apiService.mustache index edaa0f9becb..ca5e8d34968 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/apiService.mustache @@ -3,7 +3,8 @@ package {{package}}; import {{package}}.*; import {{modelPackage}}.*; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/apiServiceImpl.mustache index af1b56fc69c..7b66d35361b 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/apiServiceImpl.mustache @@ -11,7 +11,8 @@ import {{package}}.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/formParams.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/formParams.mustache index 9a7ff6ea6cf..249266065db 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/formParams.mustache @@ -1,3 +1,3 @@ {{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}){{#vendorExtensions.x-multipart}}@FormDataParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{^vendorExtensions.x-multipart}} {{#defaultValue}} @DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @FormParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/vendorExtensions.x-multipart}}{{/notFile}}{{#isFile}} @FormDataParam("{{paramName}}") InputStream {{paramName}}InputStream, - @FormDataParam("{{paramName}}") FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} + @FormDataParam("{{paramName}}") FileInfo {{paramName}}Detail{{/isFile}}{{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/pom.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/pom.mustache index ff9764e8e95..7839f9c1ec2 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/pom.mustache @@ -66,16 +66,6 @@ jackson-datatype-joda 2.4.1 - - org.glassfish.jersey.containers - jersey-container-servlet-core - ${jersey2-version} - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey2-version} - diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/serviceFormParams.mustache index dc2d2eb1ecf..c58393551df 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/serviceFormParams.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/serviceFormParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FormDataContentDisposition {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}InputStream {{paramName}}InputStream, FileInfo {{paramName}}Detail{{/isFile}}{{/isFormParam}} From af4b32178fd707f45004f9a6efa8a5f0d3b6c81b Mon Sep 17 00:00:00 2001 From: "Hamed R. Nik" Date: Thu, 3 Nov 2016 17:02:45 +0000 Subject: [PATCH 026/269] [ruby] Validate array correctly It never throws error with any values in array. Every element should be validated against the enum. --- .../src/main/resources/ruby/api.mustache | 7 +++++++ .../petstore/ruby/lib/petstore/api/fake_api.rb | 12 ++++++------ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 7071e72e849..8366246f467 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -50,9 +50,16 @@ module {{moduleName}} {{/required}} {{^required}} {{#isEnum}} + {{#collectionFormat}} + if opts[:'{{{paramName}}}'] && !opts[:'{{{paramName}}}'].all?{|item| [{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(item)} + fail ArgumentError, 'invalid value for "{{{paramName}}}", must include one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}' + end + {{/collectionFormat}} + {{^collectionFormat}} if opts[:'{{{paramName}}}'] && ![{{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}].include?(opts[:'{{{paramName}}}']) fail ArgumentError, 'invalid value for "{{{paramName}}}", must be one of {{#allowableValues}}{{#values}}{{{this}}}{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}' end + {{/collectionFormat}} {{/isEnum}} {{/required}} {{#hasValidation}} diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 0eaba370798..3500dfbb52f 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -275,20 +275,20 @@ module Petstore if @api_client.config.debugging @api_client.config.logger.debug "Calling API: FakeApi.test_enum_parameters ..." end - if opts[:'enum_form_string_array'] && !['>', '$'].include?(opts[:'enum_form_string_array']) - fail ArgumentError, 'invalid value for "enum_form_string_array", must be one of >, $' + if opts[:'enum_form_string_array'] && !opts[:'enum_form_string_array'].all?{|item| ['>', '$'].include?(item)} + fail ArgumentError, 'invalid value for "enum_form_string_array", must include one of >, $' end if opts[:'enum_form_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_form_string']) fail ArgumentError, 'invalid value for "enum_form_string", must be one of _abc, -efg, (xyz)' end - if opts[:'enum_header_string_array'] && !['>', '$'].include?(opts[:'enum_header_string_array']) - fail ArgumentError, 'invalid value for "enum_header_string_array", must be one of >, $' + if opts[:'enum_header_string_array'] && !opts[:'enum_header_string_array'].all?{|item| ['>', '$'].include?(item)} + fail ArgumentError, 'invalid value for "enum_header_string_array", must include one of >, $' end if opts[:'enum_header_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_header_string']) fail ArgumentError, 'invalid value for "enum_header_string", must be one of _abc, -efg, (xyz)' end - if opts[:'enum_query_string_array'] && !['>', '$'].include?(opts[:'enum_query_string_array']) - fail ArgumentError, 'invalid value for "enum_query_string_array", must be one of >, $' + if opts[:'enum_query_string_array'] && !opts[:'enum_query_string_array'].all?{|item| ['>', '$'].include?(item)} + fail ArgumentError, 'invalid value for "enum_query_string_array", must include one of >, $' end if opts[:'enum_query_string'] && !['_abc', '-efg', '(xyz)'].include?(opts[:'enum_query_string']) fail ArgumentError, 'invalid value for "enum_query_string", must be one of _abc, -efg, (xyz)' From 096cbd57f51731f2b996e35fed2dbec938923554 Mon Sep 17 00:00:00 2001 From: Anton WIMMER Date: Fri, 4 Nov 2016 11:47:44 +0100 Subject: [PATCH 027/269] fix[dart]: multi-word class names work properly now --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 3 ++- .../swagger-codegen/src/main/resources/dart/apilib.mustache | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index fd893f5d52f..a2e7f597c43 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -141,7 +141,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatorClass", config.getClass().toString()); config.additionalProperties().put("inputSpec", config.getInputSpec()); - + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); if (info.getTitle() != null) { @@ -405,6 +405,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); operation.put("importPath", config.toApiImport(tag)); + operation.put("classFilename", config.toApiFilename(tag)); if(!config.vendorExtensions().isEmpty()) { operation.put("vendorExtensions", config.vendorExtensions()); diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index f608cf214e0..07b02ef6105 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -16,7 +16,7 @@ part 'auth/api_key_auth.dart'; part 'auth/oauth.dart'; part 'auth/http_basic_auth.dart'; -{{#apiInfo}}{{#apis}}part 'api/{{classVarName}}_api.dart'; +{{#apiInfo}}{{#apis}}part 'api/{{classFilename}}.dart'; {{/apis}}{{/apiInfo}} {{#models}}{{#model}}part 'model/{{classFilename}}.dart'; {{/model}}{{/models}} From 51b941cf88184524e9af18e48ce013696145d9ba Mon Sep 17 00:00:00 2001 From: ircecho Date: Fri, 4 Nov 2016 12:17:23 +0100 Subject: [PATCH 028/269] DART: Removed the 'justIgnoreThisFlag' flag (#4116) * feat[dart]: remove unused argument 'justIgnoreThisFlag' * chore[dart]: petstore rebuild --- .../src/main/resources/dart/api.mustache | 6 +-- .../options/DartClientOptionsProvider.java | 2 +- .../dart/swagger/lib/api/pet_api.dart | 48 ++++--------------- .../dart/swagger/lib/api/store_api.dart | 24 ++-------- .../dart/swagger/lib/api/user_api.dart | 48 ++++--------------- 5 files changed, 22 insertions(+), 106 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache index cff22ffecf9..aaa9d5db1f4 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -12,11 +12,7 @@ class {{classname}} { /// {{summary}} /// /// {{notes}} - {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} { {{#allParams}}{{^required}} {{{dataType}}} {{paramName}}, {{/required}}{{/allParams}} bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{#required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{ {{#allParams}}{{^required}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}} }{{/hasOptionalParams}}) async { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; // verify required params are set diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java index 72066f54053..5560780eb96 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java @@ -8,7 +8,7 @@ import com.google.common.collect.ImmutableMap; import java.util.Map; public class DartClientOptionsProvider implements OptionsProvider { - public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_PARAMS_VALUE = "true"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String BROWSER_CLIENT_VALUE = "true"; public static final String PUB_NAME_VALUE = "swagger"; diff --git a/samples/client/petstore/dart/swagger/lib/api/pet_api.dart b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart index 45c203c51ef..961387012cc 100644 --- a/samples/client/petstore/dart/swagger/lib/api/pet_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/pet_api.dart @@ -10,11 +10,7 @@ class PetApi { /// Add a new pet to the store /// /// - Future addPet(Pet body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future addPet(Pet body) async { Object postBody = body; // verify required params are set @@ -65,11 +61,7 @@ class PetApi { /// Deletes a pet /// /// - Future deletePet(int petId, { String apiKey, bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future deletePet(int petId, { String apiKey }) async { Object postBody = null; // verify required params are set @@ -121,11 +113,7 @@ class PetApi { /// Finds Pets by status /// /// Multiple status values can be provided with comma separated strings - Future> findPetsByStatus(List status, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future> findPetsByStatus(List status) async { Object postBody = null; // verify required params are set @@ -177,11 +165,7 @@ class PetApi { /// Finds Pets by tags /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - Future> findPetsByTags(List tags, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future> findPetsByTags(List tags) async { Object postBody = null; // verify required params are set @@ -233,11 +217,7 @@ class PetApi { /// Find pet by ID /// /// Returns a single pet - Future getPetById(int petId, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future getPetById(int petId) async { Object postBody = null; // verify required params are set @@ -288,11 +268,7 @@ class PetApi { /// Update an existing pet /// /// - Future updatePet(Pet body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future updatePet(Pet body) async { Object postBody = body; // verify required params are set @@ -343,11 +319,7 @@ class PetApi { /// Updates a pet in the store with form data /// /// - Future updatePetWithForm(int petId, { String name, String status, bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future updatePetWithForm(int petId, { String name, String status }) async { Object postBody = null; // verify required params are set @@ -412,11 +384,7 @@ if (status != null) /// uploads an image /// /// - Future uploadFile(int petId, { String additionalMetadata, MultipartFile file, bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future uploadFile(int petId, { String additionalMetadata, MultipartFile file }) async { Object postBody = null; // verify required params are set diff --git a/samples/client/petstore/dart/swagger/lib/api/store_api.dart b/samples/client/petstore/dart/swagger/lib/api/store_api.dart index a2bf1bb68b9..9b1c4d6b6e9 100644 --- a/samples/client/petstore/dart/swagger/lib/api/store_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/store_api.dart @@ -10,11 +10,7 @@ class StoreApi { /// Delete purchase order by ID /// /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - Future deleteOrder(String orderId, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future deleteOrder(String orderId) async { Object postBody = null; // verify required params are set @@ -65,11 +61,7 @@ class StoreApi { /// Returns pet inventories by status /// /// Returns a map of status codes to quantities - Future> getInventory( { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future> getInventory() async { Object postBody = null; // verify required params are set @@ -117,11 +109,7 @@ class StoreApi { /// Find purchase order by ID /// /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - Future getOrderById(int orderId, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future getOrderById(int orderId) async { Object postBody = null; // verify required params are set @@ -172,11 +160,7 @@ class StoreApi { /// Place an order for a pet /// /// - Future placeOrder(Order body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future placeOrder(Order body) async { Object postBody = body; // verify required params are set diff --git a/samples/client/petstore/dart/swagger/lib/api/user_api.dart b/samples/client/petstore/dart/swagger/lib/api/user_api.dart index 10fecbf80f0..3632422fecd 100644 --- a/samples/client/petstore/dart/swagger/lib/api/user_api.dart +++ b/samples/client/petstore/dart/swagger/lib/api/user_api.dart @@ -10,11 +10,7 @@ class UserApi { /// Create user /// /// This can only be done by the logged in user. - Future createUser(User body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future createUser(User body) async { Object postBody = body; // verify required params are set @@ -65,11 +61,7 @@ class UserApi { /// Creates list of users with given input array /// /// - Future createUsersWithArrayInput(List body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future createUsersWithArrayInput(List body) async { Object postBody = body; // verify required params are set @@ -120,11 +112,7 @@ class UserApi { /// Creates list of users with given input array /// /// - Future createUsersWithListInput(List body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future createUsersWithListInput(List body) async { Object postBody = body; // verify required params are set @@ -175,11 +163,7 @@ class UserApi { /// Delete user /// /// This can only be done by the logged in user. - Future deleteUser(String username, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future deleteUser(String username) async { Object postBody = null; // verify required params are set @@ -230,11 +214,7 @@ class UserApi { /// Get user by user name /// /// - Future getUserByName(String username, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future getUserByName(String username) async { Object postBody = null; // verify required params are set @@ -285,11 +265,7 @@ class UserApi { /// Logs user into the system /// /// - Future loginUser(String username, String password, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future loginUser(String username, String password) async { Object postBody = null; // verify required params are set @@ -345,11 +321,7 @@ class UserApi { /// Logs out current logged in user session /// /// - Future logoutUser( { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future logoutUser() async { Object postBody = null; // verify required params are set @@ -397,11 +369,7 @@ class UserApi { /// Updated user /// /// This can only be done by the logged in user. - Future updateUser(String username, User body, { bool justIgnoreThisFlag: true}) async { - if (!justIgnoreThisFlag) { - print('Why??? Just trust me, I only need this variable inside the mustache codegen template.'); - // This code may be removed as soon as dart accepts trailing spaces (has already been implemented). - } + Future updateUser(String username, User body) async { Object postBody = body; // verify required params are set From 901a981f2614500775be8a2faab0bb12c2dff6f0 Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Fri, 4 Nov 2016 14:13:18 +0100 Subject: [PATCH 029/269] [feign] Use feign-form (#4124) * [feign] Use feign-form Fix #4108 * [feign] Convert java.util.Date params to rfc3339 with an Expander --- .../languages/AbstractJavaCodegen.java | 5 +- .../codegen/languages/JavaClientCodegen.java | 2 +- .../Java/libraries/feign/ApiClient.mustache | 3 +- .../libraries/feign/FormAwareEncoder.mustache | 192 ------------------ .../libraries/feign/ParamExpander.mustache | 22 ++ .../Java/libraries/feign/api.mustache | 7 +- .../libraries/feign/build.gradle.mustache | 2 + .../Java/libraries/feign/build.sbt.mustache | 1 + .../Java/libraries/feign/pom.mustache | 6 + .../client/petstore/java/feign/build.gradle | 2 + samples/client/petstore/java/feign/build.sbt | 1 + .../client/petstore/java/feign/gradlew.bat | 180 ++++++++-------- samples/client/petstore/java/feign/pom.xml | 6 + .../java/io/swagger/client/ApiClient.java | 3 +- .../io/swagger/client/FormAwareEncoder.java | 192 ------------------ .../java/io/swagger/client/ParamExpander.java | 22 ++ .../io/swagger/client/RFC3339DateFormat.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 9 +- .../java/io/swagger/client/api/PetApi.java | 16 +- .../java/io/swagger/client/api/StoreApi.java | 8 +- .../java/io/swagger/client/api/UserApi.java | 16 +- .../model/AdditionalPropertiesClass.java | 5 +- .../java/io/swagger/client/model/Animal.java | 5 +- .../io/swagger/client/model/AnimalFarm.java | 5 +- .../model/ArrayOfArrayOfNumberOnly.java | 5 +- .../client/model/ArrayOfNumberOnly.java | 5 +- .../io/swagger/client/model/ArrayTest.java | 5 +- .../java/io/swagger/client/model/Cat.java | 5 +- .../io/swagger/client/model/Category.java | 5 +- .../java/io/swagger/client/model/Client.java | 5 +- .../java/io/swagger/client/model/Dog.java | 5 +- .../io/swagger/client/model/EnumArrays.java | 5 +- .../io/swagger/client/model/EnumClass.java | 1 - .../io/swagger/client/model/EnumTest.java | 5 +- .../io/swagger/client/model/FormatTest.java | 5 +- .../swagger/client/model/HasOnlyReadOnly.java | 5 +- .../java/io/swagger/client/model/MapTest.java | 5 +- ...ropertiesAndAdditionalPropertiesClass.java | 5 +- .../client/model/Model200Response.java | 5 +- .../client/model/ModelApiResponse.java | 5 +- .../io/swagger/client/model/ModelReturn.java | 5 +- .../java/io/swagger/client/model/Name.java | 5 +- .../io/swagger/client/model/NumberOnly.java | 5 +- .../java/io/swagger/client/model/Order.java | 5 +- .../java/io/swagger/client/model/Pet.java | 5 +- .../swagger/client/model/ReadOnlyFirst.java | 5 +- .../client/model/SpecialModelName.java | 5 +- .../java/io/swagger/client/model/Tag.java | 5 +- .../java/io/swagger/client/model/User.java | 5 +- 49 files changed, 272 insertions(+), 561 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/feign/ParamExpander.mustache delete mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/ParamExpander.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 052a0f82316..5327a4e84cc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -273,8 +273,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code importMapping.put("LocalDate", "org.joda.time.LocalDate"); importMapping.put("DateTime", "org.joda.time.DateTime"); - } - else if (dateLibrary.startsWith("java8")) { + } else if (dateLibrary.startsWith("java8")) { additionalProperties.put("java8", "true"); typeMapping.put("date", "LocalDate"); importMapping.put("LocalDate", "java.time.LocalDate"); @@ -285,6 +284,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code typeMapping.put("DateTime", "OffsetDateTime"); importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); } + } else if (dateLibrary.equals("legacy")) { + additionalProperties.put("legacyDates", "true"); } } 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 2887e8d54c6..3c574ccebba 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 @@ -136,8 +136,8 @@ public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValida } if ("feign".equals(getLibrary())) { - supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); additionalProperties.put("jackson", "true"); + supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java")); } else if ("okhttp-gson".equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 5641afe195f..0a92f42cf73 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -18,6 +18,7 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import feign.Feign; import feign.RequestInterceptor; +import feign.form.FormEncoder; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; @@ -37,7 +38,7 @@ public class ApiClient { objectMapper = createObjectMapper(); apiAuthorizations = new LinkedHashMap(); feignBuilder = Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .encoder(new FormEncoder(new JacksonEncoder(objectMapper))) .decoder(new JacksonDecoder(objectMapper)) .logger(new Slf4jLogger()); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache deleted file mode 100644 index baf29b5f4de..00000000000 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/FormAwareEncoder.mustache +++ /dev/null @@ -1,192 +0,0 @@ -package {{invokerPackage}}; - -import java.io.*; -import java.lang.reflect.Type; -import java.net.URLEncoder; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.util.*; - -import java.text.DateFormat; - -import feign.codec.EncodeException; -import feign.codec.Encoder; -import feign.RequestTemplate; - -{{>generatedAnnotation}} -public class FormAwareEncoder implements Encoder { - public static final String UTF_8 = "utf-8"; - private static final String LINE_FEED = "\r\n"; - private static final String TWO_DASH = "--"; - private static final String BOUNDARY = "----------------314159265358979323846"; - - private byte[] lineFeedBytes; - private byte[] boundaryBytes; - private byte[] twoDashBytes; - private byte[] atBytes; - private byte[] eqBytes; - - private final Encoder delegate; - private final DateFormat dateFormat; - - public FormAwareEncoder(Encoder delegate) { - this.delegate = delegate; - this.dateFormat = new RFC3339DateFormat();; - - try { - this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); - this.boundaryBytes = BOUNDARY.getBytes(UTF_8); - this.twoDashBytes = TWO_DASH.getBytes(UTF_8); - this.atBytes = "&".getBytes(UTF_8); - this.eqBytes = "=".getBytes(UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { - if (object instanceof Map) { - try { - encodeFormParams(template, (Map) object); - } catch (IOException e) { - throw new EncodeException("Failed to create request", e); - } - } else { - delegate.encode(object, bodyType, template); - } - } - - private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - boolean isMultiPart = isMultiPart(formParams); - boolean isFirstField = true; - for (Map.Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); - if (param.getValue() instanceof File) { - addFilePart(baos, keyStr, (File) param.getValue()); - } else { - String valueStr = parameterToString(param.getValue()); - if (isMultiPart) { - addMultiPartFormField(baos, keyStr, valueStr); - } else { - addEncodedFormField(baos, keyStr, valueStr, isFirstField); - isFirstField = false; - } - } - } - - if (isMultiPart) { - baos.write(lineFeedBytes); - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(twoDashBytes); - baos.write(lineFeedBytes); - } - - String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; - template.header("Content-type"); - template.header("Content-type", contentType); - template.header("MIME-Version", "1.0"); - template.body(baos.toByteArray(), Charset.forName(UTF_8)); - } - - /* - * Currently only supports text files - */ - private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { - String fileName = uploadFile.getName(); - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(lineFeedBytes); - - String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName - + "\"; filename=\"" + fileName + "\""; - baos.write(contentDisposition.getBytes(UTF_8)); - baos.write(lineFeedBytes); - String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); - baos.write(contentType.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(lineFeedBytes); - - BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); - InputStream input = new FileInputStream(uploadFile); - byte[] bytes = new byte[4096]; - int len = bytes.length; - while ((len = input.read(bytes)) != -1) { - baos.write(bytes, 0, len); - baos.write(lineFeedBytes); - } - - baos.write(lineFeedBytes); - } - - private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { - if (!isFirstField) { - baos.write(atBytes); - } - - String encodedName = URLEncoder.encode(name, UTF_8); - String encodedValue = URLEncoder.encode(value, UTF_8); - baos.write(encodedName.getBytes(UTF_8)); - baos.write("=".getBytes(UTF_8)); - baos.write(encodedValue.getBytes(UTF_8)); - } - - private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(lineFeedBytes); - - String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; - String contentType = "Content-Type: text/plain; charset=utf-8"; - - baos.write(contentDisposition.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(contentType.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(lineFeedBytes); - baos.write(value.getBytes(UTF_8)); - baos.write(lineFeedBytes); - } - - private boolean isMultiPart(Map formParams) { - boolean isMultiPart = false; - for (Map.Entry entry : formParams.entrySet()) { - if (entry.getValue() instanceof File) { - isMultiPart = true; - break; - } - } - return isMultiPart; - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDate((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { - if(b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } -} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ParamExpander.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ParamExpander.mustache new file mode 100644 index 00000000000..2f5095d00f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ParamExpander.mustache @@ -0,0 +1,22 @@ +package {{invokerPackage}}; + +import feign.Param; + +import java.text.DateFormat; +import java.util.Date; + +/** + * Param Expander to convert {@link Date} to RFC3339 + */ +public class ParamExpander implements Param.Expander { + + private static final DateFormat dateformat = new RFC3339DateFormat(); + + @Override + public String expand(Object value) { + if (value instanceof Date) { + return dateformat.format(value); + } + return value.toString(); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index 6cb2deaccbc..a72dac0496d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -1,6 +1,9 @@ package {{package}}; import {{invokerPackage}}.ApiClient; +{{#legacyDates}} +import {{invokerPackage}}.ParamExpander; +{{/legacyDates}} {{#imports}}import {{import}}; {{/imports}} @@ -25,12 +28,12 @@ public interface {{classname}} extends ApiClient.Api { */ @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @Headers({ - "Content-type: {{vendorExtensions.x-contentType}}", + "Content-Type: {{vendorExtensions.x-contentType}}", "Accept: {{vendorExtensions.x-accepts}}",{{#headerParams}} "{{baseName}}: {{=<% %>=}}{<%paramName%>}<%={{ }}=%>"{{#hasMore}}, {{/hasMore}}{{/headerParams}} }) - {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}@Param("{{paramName}}") {{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{^isBodyParam}}{{^legacyDates}}@Param("{{paramName}}") {{/legacyDates}}{{#legacyDates}}@Param(value="{{paramName}}", expander=ParamExpander.class) {{/legacyDates}}{{/isBodyParam}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} {{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache index adbe4800eb9..0ea9d62f542 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -97,6 +97,7 @@ ext { swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" feign_version = "8.17.0" + feign_form_version = "2.0.2" junit_version = "4.12" oltu_version = "1.0.1" } @@ -106,6 +107,7 @@ dependencies { compile "com.netflix.feign:feign-core:$feign_version" compile "com.netflix.feign:feign-jackson:$feign_version" compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "io.github.openfeign.form:feign-form:$feign_form_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache index 98450123af6..d0270a99b59 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -13,6 +13,7 @@ lazy val root = (project in file(".")). "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "io.github.openfeign.form" % "feign-form" % "2.0.2" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5" % "compile", diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 027ae8a9fc4..11fc2dea148 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -125,6 +125,11 @@ feign-slf4j ${feign-version} + + io.github.openfeign.form + feign-form + ${feign-form-version} + @@ -167,6 +172,7 @@ ${java.version} 1.5.9 8.17.0 + 2.0.2 2.7.5 4.12 1.0.0 diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle index 50c4634a73f..0e13c2381b2 100644 --- a/samples/client/petstore/java/feign/build.gradle +++ b/samples/client/petstore/java/feign/build.gradle @@ -97,6 +97,7 @@ ext { swagger_annotations_version = "1.5.9" jackson_version = "2.7.5" feign_version = "8.17.0" + feign_form_version = "2.0.2" junit_version = "4.12" oltu_version = "1.0.1" } @@ -106,6 +107,7 @@ dependencies { compile "com.netflix.feign:feign-core:$feign_version" compile "com.netflix.feign:feign-jackson:$feign_version" compile "com.netflix.feign:feign-slf4j:$feign_version" + compile "io.github.openfeign.form:feign-form:$feign_form_version" compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" diff --git a/samples/client/petstore/java/feign/build.sbt b/samples/client/petstore/java/feign/build.sbt index 10b1f875927..dd67e3e7298 100644 --- a/samples/client/petstore/java/feign/build.sbt +++ b/samples/client/petstore/java/feign/build.sbt @@ -13,6 +13,7 @@ lazy val root = (project in file(".")). "com.netflix.feign" % "feign-core" % "8.16.0" % "compile", "com.netflix.feign" % "feign-jackson" % "8.17.0" % "compile", "com.netflix.feign" % "feign-slf4j" % "8.16.0" % "compile", + "io.github.openfeign.form" % "feign-form" % "2.0.2" % "compile", "com.fasterxml.jackson.core" % "jackson-core" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.7.5" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.7.5" % "compile", diff --git a/samples/client/petstore/java/feign/gradlew.bat b/samples/client/petstore/java/feign/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore/java/feign/gradlew.bat +++ b/samples/client/petstore/java/feign/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 72f588a896a..a5675bb249b 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -125,6 +125,11 @@ feign-slf4j ${feign-version} + + io.github.openfeign.form + feign-form + ${feign-form-version} + @@ -167,6 +172,7 @@ ${java.version} 1.5.9 8.17.0 + 2.0.2 2.7.5 4.12 1.0.0 diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index d4844ec8d05..68480d81e8f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -13,6 +13,7 @@ import com.fasterxml.jackson.datatype.joda.JodaModule; import feign.Feign; import feign.RequestInterceptor; +import feign.form.FormEncoder; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; @@ -32,7 +33,7 @@ public class ApiClient { objectMapper = createObjectMapper(); apiAuthorizations = new LinkedHashMap(); feignBuilder = Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .encoder(new FormEncoder(new JacksonEncoder(objectMapper))) .decoder(new JacksonDecoder(objectMapper)) .logger(new Slf4jLogger()); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java deleted file mode 100644 index 85e7fad4d72..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ /dev/null @@ -1,192 +0,0 @@ -package io.swagger.client; - -import java.io.*; -import java.lang.reflect.Type; -import java.net.URLEncoder; -import java.net.URLConnection; -import java.nio.charset.Charset; -import java.util.*; - -import java.text.DateFormat; - -import feign.codec.EncodeException; -import feign.codec.Encoder; -import feign.RequestTemplate; - - -public class FormAwareEncoder implements Encoder { - public static final String UTF_8 = "utf-8"; - private static final String LINE_FEED = "\r\n"; - private static final String TWO_DASH = "--"; - private static final String BOUNDARY = "----------------314159265358979323846"; - - private byte[] lineFeedBytes; - private byte[] boundaryBytes; - private byte[] twoDashBytes; - private byte[] atBytes; - private byte[] eqBytes; - - private final Encoder delegate; - private final DateFormat dateFormat; - - public FormAwareEncoder(Encoder delegate) { - this.delegate = delegate; - this.dateFormat = new RFC3339DateFormat();; - - try { - this.lineFeedBytes = LINE_FEED.getBytes(UTF_8); - this.boundaryBytes = BOUNDARY.getBytes(UTF_8); - this.twoDashBytes = TWO_DASH.getBytes(UTF_8); - this.atBytes = "&".getBytes(UTF_8); - this.eqBytes = "=".getBytes(UTF_8); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - } - - public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException { - if (object instanceof Map) { - try { - encodeFormParams(template, (Map) object); - } catch (IOException e) { - throw new EncodeException("Failed to create request", e); - } - } else { - delegate.encode(object, bodyType, template); - } - } - - private void encodeFormParams(RequestTemplate template, Map formParams) throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - - boolean isMultiPart = isMultiPart(formParams); - boolean isFirstField = true; - for (Map.Entry param : formParams.entrySet()) { - String keyStr = param.getKey(); - if (param.getValue() instanceof File) { - addFilePart(baos, keyStr, (File) param.getValue()); - } else { - String valueStr = parameterToString(param.getValue()); - if (isMultiPart) { - addMultiPartFormField(baos, keyStr, valueStr); - } else { - addEncodedFormField(baos, keyStr, valueStr, isFirstField); - isFirstField = false; - } - } - } - - if (isMultiPart) { - baos.write(lineFeedBytes); - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(twoDashBytes); - baos.write(lineFeedBytes); - } - - String contentType = isMultiPart ? "multipart/form-data; boundary=" + BOUNDARY : "application/x-www-form-urlencoded"; - template.header("Content-type"); - template.header("Content-type", contentType); - template.header("MIME-Version", "1.0"); - template.body(baos.toByteArray(), Charset.forName(UTF_8)); - } - - /* - * Currently only supports text files - */ - private void addFilePart(ByteArrayOutputStream baos, String fieldName, File uploadFile) throws IOException { - String fileName = uploadFile.getName(); - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(lineFeedBytes); - - String contentDisposition = "Content-Disposition: form-data; name=\"" + fieldName - + "\"; filename=\"" + fileName + "\""; - baos.write(contentDisposition.getBytes(UTF_8)); - baos.write(lineFeedBytes); - String contentType = "Content-Type: " + URLConnection.guessContentTypeFromName(fileName); - baos.write(contentType.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(lineFeedBytes); - - BufferedReader reader = new BufferedReader(new FileReader(uploadFile)); - InputStream input = new FileInputStream(uploadFile); - byte[] bytes = new byte[4096]; - int len = bytes.length; - while ((len = input.read(bytes)) != -1) { - baos.write(bytes, 0, len); - baos.write(lineFeedBytes); - } - - baos.write(lineFeedBytes); - } - - private void addEncodedFormField(ByteArrayOutputStream baos, String name, String value, boolean isFirstField) throws IOException { - if (!isFirstField) { - baos.write(atBytes); - } - - String encodedName = URLEncoder.encode(name, UTF_8); - String encodedValue = URLEncoder.encode(value, UTF_8); - baos.write(encodedName.getBytes(UTF_8)); - baos.write("=".getBytes(UTF_8)); - baos.write(encodedValue.getBytes(UTF_8)); - } - - private void addMultiPartFormField(ByteArrayOutputStream baos, String name, String value) throws IOException { - baos.write(twoDashBytes); - baos.write(boundaryBytes); - baos.write(lineFeedBytes); - - String contentDisposition = "Content-Disposition: form-data; name=\"" + name + "\""; - String contentType = "Content-Type: text/plain; charset=utf-8"; - - baos.write(contentDisposition.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(contentType.getBytes(UTF_8)); - baos.write(lineFeedBytes); - baos.write(lineFeedBytes); - baos.write(value.getBytes(UTF_8)); - baos.write(lineFeedBytes); - } - - private boolean isMultiPart(Map formParams) { - boolean isMultiPart = false; - for (Map.Entry entry : formParams.entrySet()) { - if (entry.getValue() instanceof File) { - isMultiPart = true; - break; - } - } - return isMultiPart; - } - - /** - * Format the given parameter object into string. - */ - public String parameterToString(Object param) { - if (param == null) { - return ""; - } else if (param instanceof Date) { - return formatDate((Date) param); - } else if (param instanceof Collection) { - StringBuilder b = new StringBuilder(); - for(Object o : (Collection)param) { - if(b.length() > 0) { - b.append(","); - } - b.append(String.valueOf(o)); - } - return b.toString(); - } else { - return String.valueOf(param); - } - } - - /** - * Format the given Date object into string. - */ - public String formatDate(Date date) { - return dateFormat.format(date); - } -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ParamExpander.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ParamExpander.java new file mode 100644 index 00000000000..71a6f5866b3 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ParamExpander.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +import feign.Param; + +import java.text.DateFormat; +import java.util.Date; + +/** + * Param Expander to convert {@link Date} to RFC3339 + */ +public class ParamExpander implements Param.Expander { + + private static final DateFormat dateformat = new RFC3339DateFormat(); + + @Override + public String expand(Object value) { + if (value instanceof Date) { + return dateformat.format(value); + } + return value.toString(); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java index 3d287008be5..d662f9457d7 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -1,4 +1,4 @@ -/** +/* * Swagger Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index b843c876ebb..175d35ef18c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -25,7 +25,7 @@ public interface FakeApi extends ApiClient.Api { */ @RequestLine("PATCH /fake") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) Client testClientModel(Client body); @@ -46,14 +46,15 @@ public interface FakeApi extends ApiClient.Api { * @param date None (optional) * @param dateTime None (optional) * @param password None (optional) + * @param paramCallback None (optional) * @return void */ @RequestLine("POST /fake") @Headers({ - "Content-type: application/xml; charset=utf-8", + "Content-Type: application/xml; charset=utf-8", "Accept: application/xml; charset=utf-8,application/json; charset=utf-8", }) - void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("patternWithoutDelimiter") String patternWithoutDelimiter, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("string") String string, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password); + void testEndpointParameters(@Param("number") BigDecimal number, @Param("_double") Double _double, @Param("patternWithoutDelimiter") String patternWithoutDelimiter, @Param("_byte") byte[] _byte, @Param("integer") Integer integer, @Param("int32") Integer int32, @Param("int64") Long int64, @Param("_float") Float _float, @Param("string") String string, @Param("binary") byte[] binary, @Param("date") LocalDate date, @Param("dateTime") DateTime dateTime, @Param("password") String password, @Param("paramCallback") String paramCallback); /** * To test enum parameters @@ -70,7 +71,7 @@ public interface FakeApi extends ApiClient.Api { */ @RequestLine("GET /fake?enum_query_string_array={enumQueryStringArray}&enum_query_string={enumQueryString}&enum_query_integer={enumQueryInteger}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", "enum_header_string_array: {enumHeaderStringArray}", diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index b6fbdf208dc..3c0941a7328 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -24,7 +24,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("POST /pet") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void addPet(Pet body); @@ -38,7 +38,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("DELETE /pet/{petId}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", "api_key: {apiKey}" }) @@ -52,7 +52,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("GET /pet/findByStatus?status={status}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) List findPetsByStatus(@Param("status") List status); @@ -65,7 +65,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("GET /pet/findByTags?tags={tags}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) List findPetsByTags(@Param("tags") List tags); @@ -78,7 +78,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("GET /pet/{petId}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) Pet getPetById(@Param("petId") Long petId); @@ -91,7 +91,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("PUT /pet") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void updatePet(Pet body); @@ -106,7 +106,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("POST /pet/{petId}") @Headers({ - "Content-type: application/x-www-form-urlencoded", + "Content-Type: application/x-www-form-urlencoded", "Accept: application/json", }) void updatePetWithForm(@Param("petId") Long petId, @Param("name") String name, @Param("status") String status); @@ -121,7 +121,7 @@ public interface PetApi extends ApiClient.Api { */ @RequestLine("POST /pet/{petId}/uploadImage") @Headers({ - "Content-type: multipart/form-data", + "Content-Type: multipart/form-data", "Accept: application/json", }) ModelApiResponse uploadFile(@Param("petId") Long petId, @Param("additionalMetadata") String additionalMetadata, @Param("file") File file); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index ee80acba0b4..a0d06d34dd8 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -22,7 +22,7 @@ public interface StoreApi extends ApiClient.Api { */ @RequestLine("DELETE /store/order/{orderId}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void deleteOrder(@Param("orderId") String orderId); @@ -34,7 +34,7 @@ public interface StoreApi extends ApiClient.Api { */ @RequestLine("GET /store/inventory") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) Map getInventory(); @@ -47,7 +47,7 @@ public interface StoreApi extends ApiClient.Api { */ @RequestLine("GET /store/order/{orderId}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) Order getOrderById(@Param("orderId") Long orderId); @@ -60,7 +60,7 @@ public interface StoreApi extends ApiClient.Api { */ @RequestLine("POST /store/order") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) Order placeOrder(Order body); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index 6a2c8a6afb1..d4f59bffc4c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -22,7 +22,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("POST /user") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void createUser(User body); @@ -35,7 +35,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("POST /user/createWithArray") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void createUsersWithArrayInput(List body); @@ -48,7 +48,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("POST /user/createWithList") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void createUsersWithListInput(List body); @@ -61,7 +61,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("DELETE /user/{username}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void deleteUser(@Param("username") String username); @@ -74,7 +74,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("GET /user/{username}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) User getUserByName(@Param("username") String username); @@ -88,7 +88,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("GET /user/login?username={username}&password={password}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) String loginUser(@Param("username") String username, @Param("password") String password); @@ -100,7 +100,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("GET /user/logout") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void logoutUser(); @@ -114,7 +114,7 @@ public interface UserApi extends ApiClient.Api { */ @RequestLine("PUT /user/{username}") @Headers({ - "Content-type: application/json", + "Content-Type: application/json", "Accept: application/json", }) void updateUser(@Param("username") String username, User body); diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 2da13804a0d..21e4efaeaa2 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -34,12 +34,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - /** * AdditionalPropertiesClass */ -public class AdditionalPropertiesClass { +public class AdditionalPropertiesClass { @JsonProperty("map_property") private Map mapProperty = new HashMap(); @@ -111,6 +110,7 @@ public class AdditionalPropertiesClass { return Objects.hash(mapProperty, mapOfMapProperty); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -132,5 +132,6 @@ public class AdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 346da224ad1..993f9bbe6f4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Animal */ -public class Animal { +public class Animal { @JsonProperty("className") private String className = null; @@ -98,6 +97,7 @@ public class Animal { return Objects.hash(className, color); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index 563476ccb3d..181812be4f4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -30,12 +30,11 @@ import io.swagger.client.model.Animal; import java.util.ArrayList; import java.util.List; - /** * AnimalFarm */ -public class AnimalFarm extends ArrayList { +public class AnimalFarm extends ArrayList { @Override public boolean equals(java.lang.Object o) { @@ -53,6 +52,7 @@ public class AnimalFarm extends ArrayList { return Objects.hash(super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -72,5 +72,6 @@ public class AnimalFarm extends ArrayList { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index a99f2009385..c02b8e1a37f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - /** * ArrayOfArrayOfNumberOnly */ -public class ArrayOfArrayOfNumberOnly { +public class ArrayOfArrayOfNumberOnly { @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); @@ -84,6 +83,7 @@ public class ArrayOfArrayOfNumberOnly { return Objects.hash(arrayArrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -104,5 +104,6 @@ public class ArrayOfArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 1aaf27b9921..fe97b65e190 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - /** * ArrayOfNumberOnly */ -public class ArrayOfNumberOnly { +public class ArrayOfNumberOnly { @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); @@ -84,6 +83,7 @@ public class ArrayOfNumberOnly { return Objects.hash(arrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -104,5 +104,6 @@ public class ArrayOfNumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java index 124d8bfa3a1..a035e8fe2f0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ArrayTest.java @@ -34,12 +34,11 @@ import io.swagger.client.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - /** * ArrayTest */ -public class ArrayTest { +public class ArrayTest { @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); @@ -138,6 +137,7 @@ public class ArrayTest { return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -160,5 +160,6 @@ public class ArrayTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java index 41dc312a10f..b2532f78f85 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Cat.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Cat */ -public class Cat extends Animal { +public class Cat extends Animal { @JsonProperty("declawed") private Boolean declawed = null; @@ -78,6 +77,7 @@ public class Cat extends Animal { return Objects.hash(declawed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -98,5 +98,6 @@ public class Cat extends Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index ba4ce89c297..84def6a8dac 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Category */ -public class Category { +public class Category { @JsonProperty("id") private Long id = null; @@ -98,6 +97,7 @@ public class Category { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Category { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java index 43ade4b6fcb..1540bc4d7de 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Client.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Client */ -public class Client { +public class Client { @JsonProperty("client") private String client = null; @@ -76,6 +75,7 @@ public class Client { return Objects.hash(client); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,5 +96,6 @@ public class Client { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java index 788aee5c226..d5e9063c988 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Dog.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; - /** * Dog */ -public class Dog extends Animal { +public class Dog extends Animal { @JsonProperty("breed") private String breed = null; @@ -78,6 +77,7 @@ public class Dog extends Animal { return Objects.hash(breed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -98,5 +98,6 @@ public class Dog extends Animal { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java index 45295c524f6..d8be37b302c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumArrays.java @@ -33,12 +33,11 @@ import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; - /** * EnumArrays */ -public class EnumArrays { +public class EnumArrays { /** * Gets or Sets justSymbol */ @@ -165,6 +164,7 @@ public class EnumArrays { return Objects.hash(justSymbol, arrayEnum); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -186,5 +186,6 @@ public class EnumArrays { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java index f9887c69340..c2f4ae53735 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumClass.java @@ -27,7 +27,6 @@ package io.swagger.client.model; import java.util.Objects; - import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index a7268316c40..cf3cab66458 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * EnumTest */ -public class EnumTest { +public class EnumTest { /** * Gets or Sets enumString */ @@ -210,6 +209,7 @@ public class EnumTest { return Objects.hash(enumString, enumInteger, enumNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -232,5 +232,6 @@ public class EnumTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index 2b5b4204281..df839b0898c 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -34,12 +34,11 @@ import java.math.BigDecimal; import org.joda.time.DateTime; import org.joda.time.LocalDate; - /** * FormatTest */ -public class FormatTest { +public class FormatTest { @JsonProperty("integer") private Integer integer = null; @@ -353,6 +352,7 @@ public class FormatTest { return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -385,5 +385,6 @@ public class FormatTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index d874a545244..9f59c6a47bd 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * HasOnlyReadOnly */ -public class HasOnlyReadOnly { +public class HasOnlyReadOnly { @JsonProperty("bar") private String bar = null; @@ -80,6 +79,7 @@ public class HasOnlyReadOnly { return Objects.hash(bar, foo); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -101,5 +101,6 @@ public class HasOnlyReadOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java index f8cf1ad5d1a..335dcb31cbf 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MapTest.java @@ -34,12 +34,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; - /** * MapTest */ -public class MapTest { +public class MapTest { @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); @@ -141,6 +140,7 @@ public class MapTest { return Objects.hash(mapMapOfString, mapOfEnumString); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -162,5 +162,6 @@ public class MapTest { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 20958fd50d8..af5292584ab 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -36,12 +36,11 @@ import java.util.List; import java.util.Map; import org.joda.time.DateTime; - /** * MixedPropertiesAndAdditionalPropertiesClass */ -public class MixedPropertiesAndAdditionalPropertiesClass { +public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") private String uuid = null; @@ -130,6 +129,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { return Objects.hash(uuid, dateTime, map); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -152,5 +152,6 @@ public class MixedPropertiesAndAdditionalPropertiesClass { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java index 8f48dd8020e..e905b7f9183 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Model200Response.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -public class Model200Response { +public class Model200Response { @JsonProperty("name") private Integer name = null; @@ -99,6 +98,7 @@ public class Model200Response { return Objects.hash(name, propertyClass); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -120,5 +120,6 @@ public class Model200Response { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java index 70ee2a834c0..f554939b898 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ModelApiResponse */ -public class ModelApiResponse { +public class ModelApiResponse { @JsonProperty("code") private Integer code = null; @@ -120,6 +119,7 @@ public class ModelApiResponse { return Objects.hash(code, type, message); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -142,5 +142,6 @@ public class ModelApiResponse { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java index 28294a15090..5332ff4fe2b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ModelReturn.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -public class ModelReturn { +public class ModelReturn { @JsonProperty("return") private Integer _return = null; @@ -77,6 +76,7 @@ public class ModelReturn { return Objects.hash(_return); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -97,5 +97,6 @@ public class ModelReturn { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java index 4b70e8df1a6..d26b62921fa 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Name.java @@ -31,13 +31,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -public class Name { +public class Name { @JsonProperty("name") private Integer name = null; @@ -125,6 +124,7 @@ public class Name { return Objects.hash(name, snakeCase, property, _123Number); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -148,5 +148,6 @@ public class Name { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java index ad74058d2e5..3dc6009047f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/NumberOnly.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - /** * NumberOnly */ -public class NumberOnly { +public class NumberOnly { @JsonProperty("JustNumber") private BigDecimal justNumber = null; @@ -77,6 +76,7 @@ public class NumberOnly { return Objects.hash(justNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -97,5 +97,6 @@ public class NumberOnly { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 1616b030b9d..4eea9879c86 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -32,12 +32,11 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; - /** * Order */ -public class Order { +public class Order { @JsonProperty("id") private Long id = null; @@ -219,6 +218,7 @@ public class Order { return Objects.hash(id, petId, quantity, shipDate, status, complete); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -244,5 +244,6 @@ public class Order { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index a89e0ea3e05..3ef257006ec 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -35,12 +35,11 @@ import io.swagger.client.model.Tag; import java.util.ArrayList; import java.util.List; - /** * Pet */ -public class Pet { +public class Pet { @JsonProperty("id") private Long id = null; @@ -232,6 +231,7 @@ public class Pet { return Objects.hash(id, category, name, photoUrls, tags, status); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -257,5 +257,6 @@ public class Pet { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 63e11bf14fd..0cbe504a297 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * ReadOnlyFirst */ -public class ReadOnlyFirst { +public class ReadOnlyFirst { @JsonProperty("bar") private String bar = null; @@ -89,6 +88,7 @@ public class ReadOnlyFirst { return Objects.hash(bar, baz); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -110,5 +110,6 @@ public class ReadOnlyFirst { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java index f8c5c06ca40..96bbd285945 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * SpecialModelName */ -public class SpecialModelName { +public class SpecialModelName { @JsonProperty("$special[property.name]") private Long specialPropertyName = null; @@ -76,6 +75,7 @@ public class SpecialModelName { return Objects.hash(specialPropertyName); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,5 +96,6 @@ public class SpecialModelName { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 27be94678da..330d2c8faa1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * Tag */ -public class Tag { +public class Tag { @JsonProperty("id") private Long id = null; @@ -98,6 +97,7 @@ public class Tag { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -119,5 +119,6 @@ public class Tag { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 84e3b147049..97fc77b476d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -31,12 +31,11 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** * User */ -public class User { +public class User { @JsonProperty("id") private Long id = null; @@ -230,6 +229,7 @@ public class User { return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -257,5 +257,6 @@ public class User { } return o.toString().replace("\n", "\n "); } + } From f25f6c265a88aaf7ea32ba64e516904b9b7d788e Mon Sep 17 00:00:00 2001 From: Stephan Wienczny Date: Fri, 4 Nov 2016 14:59:04 +0100 Subject: [PATCH 030/269] Update pojo.mustache Repair vendorExtensions due to broken merge. --- .../swagger-codegen/src/main/resources/Java/pojo.mustache | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 4e706ed7d4c..408c6dbe645 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -63,12 +63,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela {{/maximum}} * @return {{name}} **/ - {{#vendorExtensions.extraAnnotation}} - {{{vendorExtensions.extraAnnotation}}} - {{/vendorExtensions.extraAnnotation}} {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; From 9436ba106c97ab9fb38fcec2aa551e388cbe9a75 Mon Sep 17 00:00:00 2001 From: Stephan Wienczny Date: Fri, 4 Nov 2016 15:35:48 +0100 Subject: [PATCH 031/269] Default added sourceFolder to src/main/java Fallback to "src/main/java" for added source folder instead of a NullpointerException when no source folder ist configured in the pom --- .../src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index aca8bbf673c..1755e67750f 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -310,7 +310,10 @@ public class CodeGenMojo extends AbstractMojo { } if (addCompileSourceRoot) { - String sourceJavaFolder = output.toString() + "/" + configOptions.get(CodegenConstants.SOURCE_FOLDER); + final Object sourceFolderObject = configOptions.get(CodegenConstants.SOURCE_FOLDER); + final String sourceFolder = sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString(); + + String sourceJavaFolder = output.toString() + "/" + sourceFolder; project.addCompileSourceRoot(sourceJavaFolder); } } From a624729d70365ba735c3388268f3d2705f51203a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 4 Nov 2016 15:16:04 -0700 Subject: [PATCH 032/269] added clarification for #4138 --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 7253eea064a..69609805896 100644 --- a/README.md +++ b/README.md @@ -913,6 +913,15 @@ Here are the requirements to become a core team member: To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator. +## License information on Generated Code + +The Swagger Codegen project is intended as a benefit for users of the Swagger / Open API Specification. The project itself has the [License](#license) as specified. In addition, please understand the following points: + +* The templates included with this project are subject to the [License](#license). +* Generated code is intentionally _not_ subject to the parent project license + +When code is generated from this project, it shall be considered **AS IS** and owned by the user of the software. There are no warranties--expressed or implied--for generated code. You can do what you wish with it, and once generated, the code is your responsibility and subject to the licensing terms that you deem appropriate. + License ------- From 2f1f62e384b71e82a3d20a0d1e7b57f88de93cb6 Mon Sep 17 00:00:00 2001 From: Oleg Polosin Date: Sat, 5 Nov 2016 12:11:58 +0000 Subject: [PATCH 033/269] Added QAdept to companies list --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 69609805896..26c247a2ec0 100644 --- a/README.md +++ b/README.md @@ -792,6 +792,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) +- [QAdept](http://qadept.com/) - [QuantiModo](https://quantimo.do/) - [Rapid7](https://rapid7.com/) - [Reload! A/S](https://reload.dk/) From 1a2b345c57bdb93bdcc5fbbb76eac34854f1720e Mon Sep 17 00:00:00 2001 From: Roman Truba Date: Sat, 5 Nov 2016 18:13:51 +0300 Subject: [PATCH 034/269] [Obj-c] Generated code documentation fixes (#4130) * Fixed missing parameters names for obj-c generated code * Obj-c sample regenerated --- .../src/main/resources/objc/ApiClient-header.mustache | 2 +- .../src/main/resources/objc/Configuration-header.mustache | 6 +++--- .../resources/objc/ResponseDeserializer-header.mustache | 2 +- .../petstore/objc/default/SwaggerClient/Core/SWGApiClient.h | 2 +- .../objc/default/SwaggerClient/Core/SWGConfiguration.h | 6 +++--- .../default/SwaggerClient/Core/SWGResponseDeserializer.h | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 74ffd6f78c1..0167cd52ec4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -72,7 +72,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes * - * @param The client reachability. + * @param status The client reachability status. */ +(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index e727942a4f2..13747889d69 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -100,7 +100,7 @@ /** * Sets the prefix for API key * - * @param apiKeyPrefix API key prefix. + * @param prefix API key prefix. * @param identifier API key identifier. */ - (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; @@ -140,7 +140,7 @@ /** * Removes header from defaultHeaders * -* @param Header name. +* @param key Header name. */ -(void) removeDefaultHeaderForKey:(NSString*)key; @@ -153,7 +153,7 @@ -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; /** -* @param Header key name. +* @param key Header key name. */ -(NSString*) defaultHeaderForKey:(NSString*)key; diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache index 90aa174d7c4..774fe1ee5af 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-header.mustache @@ -28,7 +28,7 @@ extern NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode; * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. - * @param class The type of objective-c object. + * @param className The type of objective-c object. * @param error The error */ - (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h index a5f267821d8..514dd78a10a 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h @@ -98,7 +98,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes * - * @param The client reachability. + * @param status The client reachability status. */ +(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h index b6c37405ca2..5a9aec46be0 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h @@ -122,7 +122,7 @@ /** * Sets the prefix for API key * - * @param apiKeyPrefix API key prefix. + * @param prefix API key prefix. * @param identifier API key identifier. */ - (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; @@ -162,7 +162,7 @@ /** * Removes header from defaultHeaders * -* @param Header name. +* @param key Header name. */ -(void) removeDefaultHeaderForKey:(NSString*)key; @@ -175,7 +175,7 @@ -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; /** -* @param Header key name. +* @param key Header key name. */ -(NSString*) defaultHeaderForKey:(NSString*)key; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.h index c0d7b716a01..ae1c2b18b90 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.h @@ -50,7 +50,7 @@ extern NSInteger const SWGUnknownResponseObjectErrorCode; * Deserializes the given data to Objective-C object. * * @param data The data will be deserialized. - * @param class The type of objective-c object. + * @param className The type of objective-c object. * @param error The error */ - (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; From ab9ea5b2c380498745fc1e5520396987b526a937 Mon Sep 17 00:00:00 2001 From: keysolutions Date: Sat, 5 Nov 2016 11:14:48 -0400 Subject: [PATCH 035/269] Add constructFromObject to Javascript enum generation. (#4120) * Add constructFromObject to Javascript enum generation. Generated code calls constructFromObject on enum types, but enum did not define the necessary function. Returns the value of the enum. * Update Petstore JS API client --- .../Javascript/partial_model_enum_class.mustache | 9 +++++++++ .../petstore/javascript-promise/src/model/EnumClass.js | 9 +++++++++ .../client/petstore/javascript/src/model/EnumClass.js | 9 +++++++++ 3 files changed, 27 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache index 9ad7e3d3a90..39d34639916 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache @@ -20,5 +20,14 @@ {{/allowableValues}} }; + /** + * Returns a {{classname}} enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> The enum {{classname}} value. + */ + exports.constructFromObject = function(object) { + return exports[object]; + } + return exports; })); diff --git a/samples/client/petstore/javascript-promise/src/model/EnumClass.js b/samples/client/petstore/javascript-promise/src/model/EnumClass.js index 941acefddb5..9b9884b5f4b 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumClass.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumClass.js @@ -62,6 +62,15 @@ */ "(xyz)": "(xyz)" }; + /** + * Returns a EnumClass enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/EnumClass} The enum EnumClass value. + */ + exports.constructFromObject = function(object) { + return exports[object]; + } + return exports; })); diff --git a/samples/client/petstore/javascript/src/model/EnumClass.js b/samples/client/petstore/javascript/src/model/EnumClass.js index 941acefddb5..9b9884b5f4b 100644 --- a/samples/client/petstore/javascript/src/model/EnumClass.js +++ b/samples/client/petstore/javascript/src/model/EnumClass.js @@ -62,6 +62,15 @@ */ "(xyz)": "(xyz)" }; + /** + * Returns a EnumClass enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/EnumClass} The enum EnumClass value. + */ + exports.constructFromObject = function(object) { + return exports[object]; + } + return exports; })); From b355cc73816364df381b871a19d74c7216ccd21f Mon Sep 17 00:00:00 2001 From: Roman Truba Date: Sat, 5 Nov 2016 22:10:52 +0300 Subject: [PATCH 036/269] Fixed afnetworking API usage: pinnedCertificates now declared as NSSet, not as NSArray --- .../src/main/resources/objc/ApiClient-body.mustache | 2 +- .../swagger-codegen/src/main/resources/objc/podspec.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 10cb6528d86..d2acc529b5d 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -483,7 +483,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } if (config.verifySSL) { diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index bd0bd9f328e..93b3303ec31 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.public_header_files = '{{podName}}/**/*.h' {{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - s.dependency 'AFNetworking', '~> 3' + s.dependency 'AFNetworking', '~> 3.1' s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.5' end From 0c7ab639129a67ab1527a019a373e570d8f7ffa4 Mon Sep 17 00:00:00 2001 From: Roman Truba Date: Sat, 5 Nov 2016 22:11:09 +0300 Subject: [PATCH 037/269] Petstore updated --- samples/client/petstore/objc/default/SwaggerClient.podspec | 2 +- .../petstore/objc/default/SwaggerClient/Core/SWGApiClient.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/objc/default/SwaggerClient.podspec b/samples/client/petstore/objc/default/SwaggerClient.podspec index 934e35a2a6b..bebefdfc4a6 100644 --- a/samples/client/petstore/objc/default/SwaggerClient.podspec +++ b/samples/client/petstore/objc/default/SwaggerClient.podspec @@ -30,7 +30,7 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' - s.dependency 'AFNetworking', '~> 3' + s.dependency 'AFNetworking', '~> 3.1' s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m index f004200b2eb..c3c1bc453c4 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m @@ -483,7 +483,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; - [securityPolicy setPinnedCertificates:@[certData]]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; } if (config.verifySSL) { From ad1765475d90a47edeedaf17872944f5d00b2ecf Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Mon, 7 Nov 2016 03:12:59 -0500 Subject: [PATCH 038/269] [aspnet5] Fix broken template directory for deprecated lang (#4142) --- .../java/io/swagger/codegen/languages/AspNet5ServerCodegen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index d22e18f2cd0..83bbfbb6adb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -10,6 +10,8 @@ public class AspNet5ServerCodegen extends AspNetCoreServerCodegen { public AspNet5ServerCodegen() { super(); + + embeddedTemplateDir = templateDir = "aspnetcore"; } @Override From a1cd01916eb6dcfe5610860c0b21d8c5899a134b Mon Sep 17 00:00:00 2001 From: Roman Truba Date: Mon, 7 Nov 2016 18:47:09 +0300 Subject: [PATCH 039/269] [ObjC] Fix deprecated JSONModel API usage (#4133) * Fixed deprecated usage -[JSONKeyMapper initWithDictionary:] * Petstore regenerated * Change minimal required version of JSONModel --- .../swagger-codegen/src/main/resources/objc/model-body.mustache | 2 +- .../swagger-codegen/src/main/resources/objc/podspec.mustache | 2 +- .../petstore/objc/default/SwaggerClient/Model/SWGCategory.m | 2 +- .../client/petstore/objc/default/SwaggerClient/Model/SWGOrder.m | 2 +- .../client/petstore/objc/default/SwaggerClient/Model/SWGPet.m | 2 +- .../client/petstore/objc/default/SwaggerClient/Model/SWGTag.m | 2 +- .../client/petstore/objc/default/SwaggerClient/Model/SWGUser.m | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache index 5ca9303e5a8..8307a28d54a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -43,7 +43,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ {{#vars}}@"{{name}}": @"{{baseName}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } /** diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index bd0bd9f328e..ecacd4aa0af 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -31,7 +31,7 @@ Pod::Spec.new do |s| {{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} s.dependency 'AFNetworking', '~> 3' - s.dependency 'JSONModel', '~> 1.2' + s.dependency 'JSONModel', '~> 1.4' s.dependency 'ISO8601', '~> 0.5' end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGCategory.m b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGCategory.m index 00745d1f499..21e354b30e9 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGCategory.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGCategory.m @@ -17,7 +17,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_id": @"id", @"name": @"name" }]; } /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGOrder.m b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGOrder.m index e0b44e06954..7f93b0212c4 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGOrder.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGOrder.m @@ -17,7 +17,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_id": @"id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGPet.m b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGPet.m index a1c63520dc4..8c958695c88 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGPet.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGPet.m @@ -17,7 +17,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_id": @"id", @"category": @"category", @"name": @"name", @"photoUrls": @"photoUrls", @"tags": @"tags", @"status": @"status" }]; } /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGTag.m b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGTag.m index e71829873d1..3a62bcbb9a1 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGTag.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGTag.m @@ -17,7 +17,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"name": @"name" }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_id": @"id", @"name": @"name" }]; } /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGUser.m b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGUser.m index c8195660df6..fd50c02e2c9 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Model/SWGUser.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Model/SWGUser.m @@ -17,7 +17,7 @@ * This method is used by `JSONModel`. */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; + return [[JSONKeyMapper alloc] initWithModelToJSONDictionary:@{ @"_id": @"id", @"username": @"username", @"firstName": @"firstName", @"lastName": @"lastName", @"email": @"email", @"password": @"password", @"phone": @"phone", @"userStatus": @"userStatus" }]; } /** From 46c4eb3869adcf0c6b64570a90e797b753c4d015 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 7 Nov 2016 23:54:47 +0800 Subject: [PATCH 040/269] update mxf4j sample --- samples/server/petstore/java-msf4j/pom.xml | 10 ------ .../src/gen/java/io/swagger/api/FakeApi.java | 4 +-- .../java/io/swagger/api/FakeApiService.java | 32 ++++++++++++++++--- .../src/gen/java/io/swagger/api/PetApi.java | 6 ++-- .../java/io/swagger/api/PetApiService.java | 32 +++++++++++++------ .../src/gen/java/io/swagger/api/StoreApi.java | 4 +-- .../java/io/swagger/api/StoreApiService.java | 12 ++++--- .../src/gen/java/io/swagger/api/UserApi.java | 4 +-- .../java/io/swagger/api/UserApiService.java | 26 ++++++++++----- .../swagger/api/impl/FakeApiServiceImpl.java | 32 ++++++++++++++++--- .../swagger/api/impl/PetApiServiceImpl.java | 32 +++++++++++++------ .../swagger/api/impl/StoreApiServiceImpl.java | 12 ++++--- .../swagger/api/impl/UserApiServiceImpl.java | 26 ++++++++++----- 13 files changed, 163 insertions(+), 69 deletions(-) diff --git a/samples/server/petstore/java-msf4j/pom.xml b/samples/server/petstore/java-msf4j/pom.xml index b408c98d9e1..b7c61004bac 100644 --- a/samples/server/petstore/java-msf4j/pom.xml +++ b/samples/server/petstore/java-msf4j/pom.xml @@ -66,16 +66,6 @@ jackson-datatype-joda 2.4.1 - - org.glassfish.jersey.containers - jersey-container-servlet-core - ${jersey2-version} - - - org.glassfish.jersey.media - jersey-media-multipart - ${jersey2-version} - diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApi.java index ca3257cd214..1ff18daec25 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApi.java @@ -16,8 +16,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApiService.java index ae97d88b73a..33a0ff02d3c 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/FakeApiService.java @@ -3,7 +3,8 @@ package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import io.swagger.model.Client; import java.util.Date; @@ -19,7 +20,30 @@ import javax.ws.rs.core.SecurityContext; public abstract class FakeApiService { - public abstract Response testClientModel(Client body ) throws NotFoundException; - public abstract Response testEndpointParameters(BigDecimal number ,Double _double ,String patternWithoutDelimiter ,byte[] _byte ,Integer integer ,Integer int32 ,Long int64 ,Float _float ,String string ,byte[] binary ,Date date ,Date dateTime ,String password ,String paramCallback ) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray ,String enumFormString ,List enumHeaderStringArray ,String enumHeaderString ,List enumQueryStringArray ,String enumQueryString ,BigDecimal enumQueryInteger ,Double enumQueryDouble ) throws NotFoundException; + public abstract Response testClientModel(Client body + ) throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number + ,Double _double + ,String patternWithoutDelimiter + ,byte[] _byte + ,Integer integer + ,Integer int32 + ,Long int64 + ,Float _float + ,String string + ,byte[] binary + ,Date date + ,Date dateTime + ,String password + ,String paramCallback + ) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray + ,String enumFormString + ,List enumHeaderStringArray + ,String enumHeaderString + ,List enumQueryStringArray + ,String enumQueryString + ,BigDecimal enumQueryInteger + ,Double enumQueryDouble + ) throws NotFoundException; } diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApi.java index 641fcd6bd28..a6b77ddc778 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApi.java @@ -16,8 +16,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; @@ -179,7 +179,7 @@ public class PetApi { ,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata , @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail + @FormDataParam("file") FileInfo fileDetail ) throws NotFoundException { return delegate.uploadFile(petId,additionalMetadata,fileInputStream, fileDetail); diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApiService.java index cc55195c9dc..f96a1305859 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/PetApiService.java @@ -3,7 +3,8 @@ package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import io.swagger.model.Pet; import java.io.File; @@ -19,12 +20,25 @@ import javax.ws.rs.core.SecurityContext; public abstract class PetApiService { - public abstract Response addPet(Pet body ) throws NotFoundException; - public abstract Response deletePet(Long petId ,String apiKey ) throws NotFoundException; - public abstract Response findPetsByStatus(List status ) throws NotFoundException; - public abstract Response findPetsByTags(List tags ) throws NotFoundException; - public abstract Response getPetById(Long petId ) throws NotFoundException; - public abstract Response updatePet(Pet body ) throws NotFoundException; - public abstract Response updatePetWithForm(Long petId ,String name ,String status ) throws NotFoundException; - public abstract Response uploadFile(Long petId ,String additionalMetadata ,InputStream fileInputStream, FormDataContentDisposition fileDetail ) throws NotFoundException; + public abstract Response addPet(Pet body + ) throws NotFoundException; + public abstract Response deletePet(Long petId + ,String apiKey + ) throws NotFoundException; + public abstract Response findPetsByStatus(List status + ) throws NotFoundException; + public abstract Response findPetsByTags(List tags + ) throws NotFoundException; + public abstract Response getPetById(Long petId + ) throws NotFoundException; + public abstract Response updatePet(Pet body + ) throws NotFoundException; + public abstract Response updatePetWithForm(Long petId + ,String name + ,String status + ) throws NotFoundException; + public abstract Response uploadFile(Long petId + ,String additionalMetadata + ,InputStream fileInputStream, FileInfo fileDetail + ) throws NotFoundException; } diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApi.java index 4bd3369fb9c..6d6aa3848f7 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApi.java @@ -15,8 +15,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApiService.java index 40d6e37102a..58331f65bff 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/StoreApiService.java @@ -3,7 +3,8 @@ package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import java.util.Map; import io.swagger.model.Order; @@ -18,8 +19,11 @@ import javax.ws.rs.core.SecurityContext; public abstract class StoreApiService { - public abstract Response deleteOrder(String orderId ) throws NotFoundException; + public abstract Response deleteOrder(String orderId + ) throws NotFoundException; public abstract Response getInventory() throws NotFoundException; - public abstract Response getOrderById(Long orderId ) throws NotFoundException; - public abstract Response placeOrder(Order body ) throws NotFoundException; + public abstract Response getOrderById(Long orderId + ) throws NotFoundException; + public abstract Response placeOrder(Order body + ) throws NotFoundException; } diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApi.java index 6db93811a67..fe7159324b9 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApi.java @@ -15,8 +15,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApiService.java index 2d41ae3a61d..5042a551342 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/api/UserApiService.java @@ -3,7 +3,8 @@ package io.swagger.api; import io.swagger.api.*; import io.swagger.model.*; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import io.swagger.model.User; import java.util.List; @@ -18,12 +19,21 @@ import javax.ws.rs.core.SecurityContext; public abstract class UserApiService { - public abstract Response createUser(User body ) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body ) throws NotFoundException; - public abstract Response createUsersWithListInput(List body ) throws NotFoundException; - public abstract Response deleteUser(String username ) throws NotFoundException; - public abstract Response getUserByName(String username ) throws NotFoundException; - public abstract Response loginUser(String username ,String password ) throws NotFoundException; + public abstract Response createUser(User body + ) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body + ) throws NotFoundException; + public abstract Response createUsersWithListInput(List body + ) throws NotFoundException; + public abstract Response deleteUser(String username + ) throws NotFoundException; + public abstract Response getUserByName(String username + ) throws NotFoundException; + public abstract Response loginUser(String username + ,String password + ) throws NotFoundException; public abstract Response logoutUser() throws NotFoundException; - public abstract Response updateUser(String username ,User body ) throws NotFoundException; + public abstract Response updateUser(String username + ,User body + ) throws NotFoundException; } diff --git a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index f4fb6865495..43e07c14462 100644 --- a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -12,7 +12,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -20,17 +21,40 @@ import javax.ws.rs.core.SecurityContext; public class FakeApiServiceImpl extends FakeApiService { @Override - public Response testClientModel(Client body ) throws NotFoundException { + public Response testClientModel(Client body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback ) throws NotFoundException { + public Response testEndpointParameters(BigDecimal number +, Double _double +, String patternWithoutDelimiter +, byte[] _byte +, Integer integer +, Integer int32 +, Long int64 +, Float _float +, String string +, byte[] binary +, Date date +, Date dateTime +, String password +, String paramCallback + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble ) throws NotFoundException { + public Response testEnumParameters(List enumFormStringArray +, String enumFormString +, List enumHeaderStringArray +, String enumHeaderString +, List enumQueryStringArray +, String enumQueryString +, BigDecimal enumQueryInteger +, Double enumQueryDouble + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index e99c9fa1e75..ea6b7553a52 100644 --- a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -12,7 +12,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -20,42 +21,55 @@ import javax.ws.rs.core.SecurityContext; public class PetApiServiceImpl extends PetApiService { @Override - public Response addPet(Pet body ) throws NotFoundException { + public Response addPet(Pet body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response deletePet(Long petId, String apiKey ) throws NotFoundException { + public Response deletePet(Long petId +, String apiKey + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByStatus(List status ) throws NotFoundException { + public Response findPetsByStatus(List status + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByTags(List tags ) throws NotFoundException { + public Response findPetsByTags(List tags + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getPetById(Long petId ) throws NotFoundException { + public Response getPetById(Long petId + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response updatePet(Pet body ) throws NotFoundException { + public Response updatePet(Pet body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response updatePetWithForm(Long petId, String name, String status ) throws NotFoundException { + public Response updatePetWithForm(Long petId +, String name +, String status + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail ) throws NotFoundException { + public Response uploadFile(Long petId +, String additionalMetadata +, InputStream fileInputStream, FileInfo fileDetail + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 9df17bebc17..cc9af6a7597 100644 --- a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -11,7 +11,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -19,7 +20,8 @@ import javax.ws.rs.core.SecurityContext; public class StoreApiServiceImpl extends StoreApiService { @Override - public Response deleteOrder(String orderId ) throws NotFoundException { + public Response deleteOrder(String orderId + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @@ -29,12 +31,14 @@ public class StoreApiServiceImpl extends StoreApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getOrderById(Long orderId ) throws NotFoundException { + public Response getOrderById(Long orderId + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response placeOrder(Order body ) throws NotFoundException { + public Response placeOrder(Order body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index bab444ea620..babd595dca8 100644 --- a/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/java-msf4j/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -11,7 +11,8 @@ import io.swagger.api.NotFoundException; import java.io.InputStream; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.wso2.msf4j.formparam.FormDataParam; +import org.wso2.msf4j.formparam.FileInfo; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -19,32 +20,39 @@ import javax.ws.rs.core.SecurityContext; public class UserApiServiceImpl extends UserApiService { @Override - public Response createUser(User body ) throws NotFoundException { + public Response createUser(User body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List body ) throws NotFoundException { + public Response createUsersWithArrayInput(List body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List body ) throws NotFoundException { + public Response createUsersWithListInput(List body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response deleteUser(String username ) throws NotFoundException { + public Response deleteUser(String username + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getUserByName(String username ) throws NotFoundException { + public Response getUserByName(String username + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response loginUser(String username, String password ) throws NotFoundException { + public Response loginUser(String username +, String password + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @@ -54,7 +62,9 @@ public class UserApiServiceImpl extends UserApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response updateUser(String username, User body ) throws NotFoundException { + public Response updateUser(String username +, User body + ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } From 37460ee833fd31a1f363037aa7a3950ade104307 Mon Sep 17 00:00:00 2001 From: mbohlool Date: Mon, 7 Nov 2016 11:48:30 -0800 Subject: [PATCH 041/269] Select application/json content-type in python generated client, if */* is in the list of content-types --- .../src/main/resources/python/api_client.mustache | 2 +- samples/client/petstore/python/petstore_api/api_client.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 0a5864a81af..dc4fe509f62 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -462,7 +462,7 @@ class ApiClient(object): content_types = list(map(lambda x: x.lower(), content_types)) - if 'application/json' in content_types: + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0] diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index adf66173dbc..bd57c1089a4 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -462,7 +462,7 @@ class ApiClient(object): content_types = list(map(lambda x: x.lower(), content_types)) - if 'application/json' in content_types: + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0] From 935bdfe6280eea9f32a30d76bee2801b763c3ac9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 8 Nov 2016 16:17:51 +0800 Subject: [PATCH 042/269] better handling of */* --- .../main/java/io/swagger/codegen/DefaultCodegen.java | 12 ++++++++++-- .../src/main/resources/ruby/api_client.mustache | 3 ++- ...store-with-fake-endpoints-models-for-testing.yaml | 4 ++-- samples/client/petstore/ruby/docs/FakeApi.md | 4 ++-- .../petstore/ruby/lib/petstore/api/fake_api.rb | 4 ++-- .../client/petstore/ruby/lib/petstore/api_client.rb | 3 ++- 6 files changed, 20 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 23bfb825bea..63cad401d02 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1892,7 +1892,11 @@ public class DefaultCodegen { for (String key : consumes) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + if ("*/*".equals(key)) { // "*/*" is a special case, do nothing + mediaType.put("mediaType", key); + } else { + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + } count += 1; if (count < consumes.size()) { mediaType.put("hasMore", "true"); @@ -1926,7 +1930,11 @@ public class DefaultCodegen { for (String key : produces) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + if ("*/*".equals(key)) { // "*/*" is a special case, do nothing + mediaType.put("mediaType", key); + } else { + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); + } count += 1; if (count < produces.size()) { mediaType.put("hasMore", "true"); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index fcd4b3eebfa..7fa611e3744 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -125,10 +125,11 @@ module {{moduleName}} # application/json # application/json; charset=UTF8 # APPLICATION/JSON + # */* # @param [String] mime MIME # @return [Boolean] True if the MIME is application/json def json_mime?(mime) - !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? + (mime == "*/*") || !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end # Deserialize the response to the given return type. diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index c42dc774a22..4666a0cc167 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -590,9 +590,9 @@ paths: descriptions: To test enum parameters operationId: testEnumParameters consumes: - - application/json + - "*/*" produces: - - application/json + - "*/*" parameters: - name: enum_form_string_array type: array diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 1524d9c915f..971fdadb1ae 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -191,8 +191,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json - - **Accept**: application/json + - **Content-Type**: */* + - **Accept**: */* diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 3500dfbb52f..a9c7cf07710 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -306,11 +306,11 @@ module Petstore header_params = {} # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json'] + local_header_accept = ['*/*'] local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result # HTTP header 'Content-Type' - local_header_content_type = ['application/json'] + local_header_content_type = ['*/*'] header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 0a95711ce43..64cc2e286c2 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -142,10 +142,11 @@ module Petstore # application/json # application/json; charset=UTF8 # APPLICATION/JSON + # */* # @param [String] mime MIME # @return [Boolean] True if the MIME is application/json def json_mime?(mime) - !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? + (mime == "*/*") || !(mime =~ /\Aapplication\/json(;.*)?\z/i).nil? end # Deserialize the response to the given return type. From cce410c4634f54aee9ed6605c87ce5bdfa412fb9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 8 Nov 2016 21:06:38 +0800 Subject: [PATCH 043/269] add vendor extension to handle void response in jaxrs-cxf --- .../AbstractJavaJAXRSServerCodegen.java | 3 + .../JavaJaxRS/cxf/apiServiceImpl.mustache | 2 +- pom.xml | 12 + samples/server/petstore/jaxrs-cxf/pom.xml | 222 ++++++------------ samples/server/petstore/jaxrs/jersey2/pom.xml | 8 + .../src/gen/java/io/swagger/api/FakeApi.java | 4 +- .../model/AdditionalPropertiesClass.java | 26 ++ .../src/gen/java/io/swagger/model/Animal.java | 26 ++ .../gen/java/io/swagger/model/AnimalFarm.java | 26 ++ .../model/ArrayOfArrayOfNumberOnly.java | 26 ++ .../io/swagger/model/ArrayOfNumberOnly.java | 26 ++ .../gen/java/io/swagger/model/ArrayTest.java | 26 ++ .../src/gen/java/io/swagger/model/Cat.java | 26 ++ .../gen/java/io/swagger/model/Category.java | 26 ++ .../src/gen/java/io/swagger/model/Client.java | 26 ++ .../src/gen/java/io/swagger/model/Dog.java | 26 ++ .../gen/java/io/swagger/model/EnumArrays.java | 26 ++ .../gen/java/io/swagger/model/EnumClass.java | 26 +- .../gen/java/io/swagger/model/EnumTest.java | 26 ++ .../gen/java/io/swagger/model/FormatTest.java | 26 ++ .../io/swagger/model/HasOnlyReadOnly.java | 26 ++ .../gen/java/io/swagger/model/MapTest.java | 26 ++ ...ropertiesAndAdditionalPropertiesClass.java | 26 ++ .../io/swagger/model/Model200Response.java | 26 ++ .../io/swagger/model/ModelApiResponse.java | 26 ++ .../java/io/swagger/model/ModelReturn.java | 26 ++ .../src/gen/java/io/swagger/model/Name.java | 26 ++ .../gen/java/io/swagger/model/NumberOnly.java | 26 ++ .../src/gen/java/io/swagger/model/Order.java | 26 ++ .../src/gen/java/io/swagger/model/Pet.java | 26 ++ .../java/io/swagger/model/ReadOnlyFirst.java | 26 ++ .../io/swagger/model/SpecialModelName.java | 26 ++ .../src/gen/java/io/swagger/model/Tag.java | 26 ++ .../src/gen/java/io/swagger/model/User.java | 26 ++ 34 files changed, 820 insertions(+), 159 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index de0812c40f8..af961e9983b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -139,8 +139,11 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen } } } + if ( operation.returnType == null ) { operation.returnType = "void"; + // set vendorExtensions.x-java-is-response-void to true as returnType is set to "void" + operation.vendorExtensions.put("x-java-is-response-void", true); } else if ( operation.returnType.startsWith("List") ) { String rt = operation.returnType; int end = rt.lastIndexOf(">"); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index 9b55d4c7551..c0199a9b5ca 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -25,7 +25,7 @@ public class {{classname}}ServiceImpl implements {{classname}} { public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... - {{#returnType}}return null;{{/returnType}} + {{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}} } {{/operation}} diff --git a/pom.xml b/pom.xml index 14183730254..562011ff714 100644 --- a/pom.xml +++ b/pom.xml @@ -463,6 +463,18 @@ samples/server/petstore/java-msf4/ + + jaxrs-cxf-server + + + env + java + + + + samples/server/petstore/jaxrs-cxf + + jaxrs-resteasy-server diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml index 6b0b2318022..24ae04f9d19 100644 --- a/samples/server/petstore/jaxrs-cxf/pom.xml +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -1,18 +1,13 @@ 4.0.0 io.swagger - swagger-jaxrs-cxf-server - jar - swagger-jaxrs-cxf-server + swagger-cxf-server + war + swagger-cxf-server 1.0.0 - gen/main/java + src/main/java - - org.apache.maven.plugins - maven-war-plugin - 2.1.1 - maven-failsafe-plugin 2.6 @@ -25,7 +20,7 @@ - + org.codehaus.mojo build-helper-maven-plugin @@ -76,143 +70,87 @@ - gen/java + src/gen/java + + + + maven-war-plugin + 2.1.1 + + true + + - - - org.springframework - spring-context - ${springframework-version} + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} - - org.springframework - spring-context-support - ${springframework-version} - - - org.springframework - spring-web - ${springframework-version} - - - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf-version} - - - - org.apache.cxf - cxf-rt-transports-http - ${cxf-version} - - - - org.apache.cxf - cxf-rt-rs-extension-providers - ${cxf-version} - - - - javax.ws.rs - jsr311-api - 1.1.1 - - - - - org.slf4j - slf4j-api - ${slf4j-version} - - - - - org.slf4j - log4j-over-slf4j - ${slf4j-version} - runtime - - - - org.slf4j - jcl-over-slf4j - ${slf4j-version} - - - - org.slf4j - jul-to-slf4j - ${slf4j-version} - - ch.qos.logback logback-classic - 1.0.9 - runtime - - - - - - - - javax.servlet - servlet-api - ${servlet-api-version} - provided - - - org.scala-lang - scala-library - ${scala-version} + ch.qos.logback + logback-core + ${logback-version} + compile - - - org.springframework - spring-test - ${springframework-version} - test - - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf-version} - test - - - - org.scalatest - scalatest_2.10 - ${scala-test-version} - test - - junit junit ${junit-version} test - + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description-swagger + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + @@ -229,37 +167,11 @@ ${java.version} 1.5.9 9.2.9.v20150224 - 1.19.1 - 1.7.21 + 2.22.2 4.12 + 1.1.7 2.5 + 3.1.7 UTF-8 - 3.2.1.RELEASE - 2.7.15 - - 1.2 - 2.2 - 1.5.10 - 2.1.4 - 2.10.4 - 2.3.4 - 2.5 - 1.13 - 2.1 - 2.4.2 - 2.4.2 - 1.0.1 - - 4.8.1 - 1.0.0 - 3.2.1 - 1.6.3 - 2.1.3 - 8.1.11.v20130520 - 3.1.5 - 0.90 - 0.90 - 0 - diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index bc2bc84665d..5f3f512a42d 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -124,6 +124,14 @@ jersey-media-multipart ${jersey2-version} + + + com.brsanthu + migbase64 + 2.2 + + + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java index 40d9a325beb..b47b9daa7dc 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java @@ -75,8 +75,8 @@ public class FakeApi { } @GET - @Consumes({ "application/json" }) - @Produces({ "application/json" }) + @Consumes({ "*/*" }) + @Produces({ "*/*" }) @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index f74f7d3d882..25d3c688b79 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -85,6 +110,7 @@ public class AdditionalPropertiesClass { return Objects.hash(mapProperty, mapOfMapProperty); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java index de739ed501c..bf237d9b68b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -72,6 +97,7 @@ public class Animal { return Objects.hash(className, color); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java index c2b0084d9cd..7d6310bcb5d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -27,6 +52,7 @@ public class AnimalFarm extends ArrayList { return Objects.hash(super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 803eb69e16a..514dc8c1392 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -58,6 +83,7 @@ public class ArrayOfArrayOfNumberOnly { return Objects.hash(arrayArrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index bebc2470927..ed1c4eae818 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -58,6 +83,7 @@ public class ArrayOfNumberOnly { return Objects.hash(arrayNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java index 19464a99acd..b88dca900f5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -112,6 +137,7 @@ public class ArrayTest { return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java index 95bea570923..cb618f4b188 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -52,6 +77,7 @@ public class Cat extends Animal { return Objects.hash(declawed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index ba1ecfdb2b8..3bbb55c96fd 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -72,6 +97,7 @@ public class Category { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java index fcb2b0a8340..dd85b694889 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -50,6 +75,7 @@ public class Client { return Objects.hash(client); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java index f8072688756..c6b58b52202 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -52,6 +77,7 @@ public class Dog extends Animal { return Objects.hash(breed, super.hashCode()); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java index 959b35e6b13..f9dae7c4989 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -142,6 +167,7 @@ public class EnumArrays { return Objects.hash(justSymbol, arrayEnum); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java index d8ac42c4872..7786ccdc589 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -23,7 +48,6 @@ public enum EnumClass { } @Override - @JsonValue public String toString() { return String.valueOf(value); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java index 446649217c8..fb4c755f11c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -188,6 +213,7 @@ public class EnumTest { return Objects.hash(enumString, enumInteger, enumNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index 7c882eb3fee..1c09d9b83dc 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -326,6 +351,7 @@ public class FormatTest { return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 3f5492a2e62..3ed2e826909 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -54,6 +79,7 @@ public class HasOnlyReadOnly { return Objects.hash(bar, foo); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java index 9ef30a045d0..06d5876ce65 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -117,6 +142,7 @@ public class MapTest { return Objects.hash(mapMapOfString, mapOfEnumString); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 5a55ab81d68..4691a6be9b8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -104,6 +129,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { return Objects.hash(uuid, dateTime, map); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java index 09ad4d0d60e..3221e2e3c64 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -73,6 +98,7 @@ public class Model200Response { return Objects.hash(name, propertyClass); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java index 82f447004ee..6ac7d14a1fc 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -94,6 +119,7 @@ public class ModelApiResponse { return Objects.hash(code, type, message); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java index 884a45c598e..afdea1f37d1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -51,6 +76,7 @@ public class ModelReturn { return Objects.hash(_return); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java index 09085fb52dc..ad4b96845aa 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -99,6 +124,7 @@ public class Name { return Objects.hash(name, snakeCase, property, _123Number); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java index 9424f7a4b5e..f88928c72a2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -51,6 +76,7 @@ public class NumberOnly { return Objects.hash(justNumber); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index 1dfe20badf0..066e07c8825 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -195,6 +220,7 @@ public class Order { return Objects.hash(id, petId, quantity, shipDate, status, complete); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index 823d25e05a0..570ea396090 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -208,6 +233,7 @@ public class Pet { return Objects.hash(id, category, name, photoUrls, tags, status); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 50a2a7e4184..94030bc0d76 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -63,6 +88,7 @@ public class ReadOnlyFirst { return Objects.hash(bar, baz); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java index 2cdc99de90e..d5acd14ac66 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -50,6 +75,7 @@ public class SpecialModelName { return Objects.hash(specialPropertyName); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index 846812a5031..c8f9cec4a9b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -72,6 +97,7 @@ public class Tag { return Objects.hash(id, name); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 52c5fff826e..d932649a4e5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -1,3 +1,28 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package io.swagger.model; import java.util.Objects; @@ -204,6 +229,7 @@ public class User { return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); From 6d6cfb49843271c514fc98218269a139b23ed2df Mon Sep 17 00:00:00 2001 From: Anton WIMMER Date: Tue, 8 Nov 2016 14:29:27 +0100 Subject: [PATCH 044/269] fix[dart]: send ISO8601 dates --- .../main/resources/dart/api_client.mustache | 19 ------------------- .../main/resources/dart/api_helper.mustache | 17 ++++++++++++++--- .../src/main/resources/dart/apilib.mustache | 1 - .../src/main/resources/dart/pubspec.mustache | 1 - .../client/petstore/dart/swagger/lib/api.dart | 1 - .../petstore/dart/swagger/lib/api_client.dart | 19 ------------------- .../petstore/dart/swagger/lib/api_helper.dart | 17 ++++++++++++++--- .../client/petstore/dart/swagger/pubspec.yaml | 1 - 8 files changed, 28 insertions(+), 48 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache index dcbd731d2af..86e698eb836 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -17,7 +17,6 @@ class ApiClient { final dson = new Dartson.JSON() ..addTransformer(new DateTimeParser(), DateTime); - final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); final _RegList = new RegExp(r'^List<(.*)>$'); final _RegMap = new RegExp(r'^Map$'); @@ -33,24 +32,6 @@ class ApiClient { _defaultHeaderMap[key] = value; } - /// Format the given Date object into string. - String formatDate(DateTime date) { - return _dateFormatter.format(date); - } - - /// Format the given parameter object into string. - String parameterToString(Object param) { - if (param == null) { - return ''; - } else if (param is DateTime) { - return formatDate(param); - } else if (param is List) { - return (param).join(','); - } else { - return param.toString(); - } - } - dynamic _deserialize(dynamic value, String targetType) { try { switch (targetType) { diff --git a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache index 6052dfb312b..15798ef3466 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_helper.mustache @@ -11,7 +11,7 @@ Iterable _convertParametersForCollectionFormat( if (name == null || name.isEmpty || value == null) return params; if (value is! List) { - params.add(new QueryParam(name, '$value')); + params.add(new QueryParam(name, _parameterToString(value))); return params; } @@ -23,11 +23,22 @@ Iterable _convertParametersForCollectionFormat( : collectionFormat; // default: csv if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, '$v')); + return values.map((v) => new QueryParam(name, _parameterToString(v))); } String delimiter = _delimiters[collectionFormat] ?? ","; - params.add(new QueryParam(name, values.join(delimiter))); + params.add(new QueryParam(name, values.map((v)=>_parameterToString(v)).join(delimiter))); return params; } + +/// Format the given parameter object into string. +String _parameterToString(dynamic value) { + if (value == null) { + return ''; + } else if (value is DateTime) { + return value.toUtc().toIso8601String(); + } else { + return value.toString(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache index 07b02ef6105..8f131054f25 100644 --- a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -6,7 +6,6 @@ import 'package:http/browser_client.dart';{{/browserClient}} import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; import 'package:dartson/transformers/date_time.dart'; -import 'package:intl/intl.dart'; part 'api_client.dart'; part 'api_helper.dart'; diff --git a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache index ce0a309ea82..5a580b2696d 100644 --- a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache @@ -4,7 +4,6 @@ description: {{pubDescription}} dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - intl: ">=0.12.4" dev_dependencies: guinness: '^0.1.17' diff --git a/samples/client/petstore/dart/swagger/lib/api.dart b/samples/client/petstore/dart/swagger/lib/api.dart index db95000d614..9273d7f1f99 100644 --- a/samples/client/petstore/dart/swagger/lib/api.dart +++ b/samples/client/petstore/dart/swagger/lib/api.dart @@ -6,7 +6,6 @@ import 'package:http/browser_client.dart'; import 'package:http/http.dart'; import 'package:dartson/dartson.dart'; import 'package:dartson/transformers/date_time.dart'; -import 'package:intl/intl.dart'; part 'api_client.dart'; part 'api_helper.dart'; diff --git a/samples/client/petstore/dart/swagger/lib/api_client.dart b/samples/client/petstore/dart/swagger/lib/api_client.dart index 73856b69d74..9552cef10d8 100644 --- a/samples/client/petstore/dart/swagger/lib/api_client.dart +++ b/samples/client/petstore/dart/swagger/lib/api_client.dart @@ -17,7 +17,6 @@ class ApiClient { final dson = new Dartson.JSON() ..addTransformer(new DateTimeParser(), DateTime); - final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); final _RegList = new RegExp(r'^List<(.*)>$'); final _RegMap = new RegExp(r'^Map$'); @@ -32,24 +31,6 @@ class ApiClient { _defaultHeaderMap[key] = value; } - /// Format the given Date object into string. - String formatDate(DateTime date) { - return _dateFormatter.format(date); - } - - /// Format the given parameter object into string. - String parameterToString(Object param) { - if (param == null) { - return ''; - } else if (param is DateTime) { - return formatDate(param); - } else if (param is List) { - return (param).join(','); - } else { - return param.toString(); - } - } - dynamic _deserialize(dynamic value, String targetType) { try { switch (targetType) { diff --git a/samples/client/petstore/dart/swagger/lib/api_helper.dart b/samples/client/petstore/dart/swagger/lib/api_helper.dart index ad73218ab40..7d2c3471a9f 100644 --- a/samples/client/petstore/dart/swagger/lib/api_helper.dart +++ b/samples/client/petstore/dart/swagger/lib/api_helper.dart @@ -11,7 +11,7 @@ Iterable _convertParametersForCollectionFormat( if (name == null || name.isEmpty || value == null) return params; if (value is! List) { - params.add(new QueryParam(name, '$value')); + params.add(new QueryParam(name, _parameterToString(value))); return params; } @@ -23,11 +23,22 @@ Iterable _convertParametersForCollectionFormat( : collectionFormat; // default: csv if (collectionFormat == "multi") { - return values.map((v) => new QueryParam(name, '$v')); + return values.map((v) => new QueryParam(name, _parameterToString(v))); } String delimiter = _delimiters[collectionFormat] ?? ","; - params.add(new QueryParam(name, values.join(delimiter))); + params.add(new QueryParam(name, values.map((v)=>_parameterToString(v)).join(delimiter))); return params; } + +/// Format the given parameter object into string. +String _parameterToString(dynamic value) { + if (value == null) { + return ''; + } else if (value is DateTime) { + return value.toUtc().toIso8601String(); + } else { + return value.toString(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/dart/swagger/pubspec.yaml b/samples/client/petstore/dart/swagger/pubspec.yaml index 8ad53b9d6e6..50938a1c095 100644 --- a/samples/client/petstore/dart/swagger/pubspec.yaml +++ b/samples/client/petstore/dart/swagger/pubspec.yaml @@ -4,7 +4,6 @@ description: Swagger API client dependencies: http: '>=0.11.1 <0.12.0' dartson: "^0.2.4" - intl: ">=0.12.4" dev_dependencies: guinness: '^0.1.17' From ba9e449fd43d1dc62f7f2af693b64b3c64f4fa8e Mon Sep 17 00:00:00 2001 From: mbohlool Date: Thu, 10 Nov 2016 07:43:32 -0800 Subject: [PATCH 045/269] Support _preload_content flag in python client (#4166) * Modify python client templates to support _preload_content flag * Update python petstore --- .../src/main/resources/python/api.mustache | 2 + .../main/resources/python/api_client.mustache | 39 ++++++++++------ .../src/main/resources/python/rest.mustache | 45 ++++++++++++------- .../client/petstore/python/docs/FakeApi.md | 4 +- .../python/petstore_api/api_client.py | 39 ++++++++++------ .../python/petstore_api/apis/fake_api.py | 10 ++++- .../python/petstore_api/apis/pet_api.py | 16 +++++++ .../python/petstore_api/apis/store_api.py | 8 ++++ .../python/petstore_api/apis/user_api.py | 16 +++++++ .../petstore/python/petstore_api/rest.py | 45 ++++++++++++------- 10 files changed, 162 insertions(+), 62 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 2d86c9de66c..c6a07b2f7a2 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -98,6 +98,7 @@ class {{classname}}(object): all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -211,6 +212,7 @@ class {{classname}}(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index dc4fe509f62..11646705495 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -96,7 +96,7 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True): # header parameters header_params = header_params or {} @@ -144,22 +144,24 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) + post_params=post_params, body=body, _preload_content=_preload_content) self.last_response = response_data - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None + return_data = response_data + if _preload_content: + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if callback: - callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) + callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return (deserialized_data) + return (return_data) else: - return (deserialized_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, response_data.getheaders()) def sanitize_for_serialization(self, obj): """ @@ -277,7 +279,7 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -307,13 +309,15 @@ class ApiClient(object): The method will return the request thread. If parameter callback is None, then the method will return the response directly. + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. """ if callback is None: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats) + _return_http_data_only, collection_formats, _preload_content) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,51 +326,58 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats)) + collection_formats, _preload_content)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): + post_params=None, body=None, _preload_content=True): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, + _preload_content=_preload_content, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, + _preload_content=_preload_content, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, + _preload_content=_preload_content, body=body) else: raise ValueError( diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 9bdddc91904..3f0e3dca292 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -85,7 +85,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None): + body=None, post_params=None, _preload_content=True): """ :param method: http request method :param url: http request url @@ -95,6 +95,8 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] @@ -121,11 +123,13 @@ class RESTClientObject(object): request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, + preload_content=_preload_content, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type @@ -134,6 +138,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=True, + preload_content=_preload_content, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided @@ -142,6 +147,7 @@ class RESTClientObject(object): request_body = body r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, headers=headers) else: # Cannot generate the request from given parameters @@ -152,68 +158,77 @@ class RESTClientObject(object): else: r = self.pool_manager.request(method, url, fields=query_params, + preload_content=_preload_content, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - r = RESTResponse(r) + if _preload_content: + r = RESTResponse(r) - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if PY3: - r.data = r.data.decode('utf8') + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if PY3: + r.data = r.data.decode('utf8') - # log response body - logger.debug("response body: %s", r.data) + # log response body + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) return r - def GET(self, url, headers=None, query_params=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True): return self.request("GET", url, headers=headers, + _preload_content=_preload_content, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True): return self.request("HEAD", url, headers=headers, + _preload_content=_preload_content, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None): + def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True): return self.request("DELETE", url, headers=headers, query_params=query_params, + _preload_content=_preload_content, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index c6ed3ccfbfc..69186f43a50 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -186,8 +186,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json - - **Accept**: application/json + - **Content-Type**: */* + - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index bd57c1089a4..f13cb3772ad 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -96,7 +96,7 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True): # header parameters header_params = header_params or {} @@ -144,22 +144,24 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) + post_params=post_params, body=body, _preload_content=_preload_content) self.last_response = response_data - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None + return_data = response_data + if _preload_content: + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if callback: - callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) + callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return (deserialized_data) + return (return_data) else: - return (deserialized_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, response_data.getheaders()) def sanitize_for_serialization(self, obj): """ @@ -277,7 +279,7 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -307,13 +309,15 @@ class ApiClient(object): The method will return the request thread. If parameter callback is None, then the method will return the response directly. + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. """ if callback is None: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats) + _return_http_data_only, collection_formats, _preload_content) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,51 +326,58 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats)) + collection_formats, _preload_content)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): + post_params=None, body=None, _preload_content=True): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, + _preload_content=_preload_content, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, + _preload_content=_preload_content, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, + _preload_content=_preload_content, body=body) else: raise ValueError( diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 944396a9fdc..cdf79483bc9 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -102,6 +102,7 @@ class FakeApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -157,6 +158,7 @@ class FakeApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): @@ -236,6 +238,7 @@ class FakeApi(object): all_params = ['number', 'double', 'pattern_without_delimiter', 'byte', 'integer', 'int32', 'int64', 'float', 'string', 'binary', 'date', 'date_time', 'password', 'param_callback'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -352,6 +355,7 @@ class FakeApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def test_enum_parameters(self, **kwargs): @@ -419,6 +423,7 @@ class FakeApi(object): all_params = ['enum_form_string_array', 'enum_form_string', 'enum_header_string_array', 'enum_header_string', 'enum_query_string_array', 'enum_query_string', 'enum_query_integer', 'enum_query_double'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -466,13 +471,13 @@ class FakeApi(object): # HTTP header `Accept` header_params['Accept'] = self.api_client.\ - select_header_accept(['application/json']) + select_header_accept(['*/*']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ - select_header_content_type(['application/json']) + select_header_content_type(['*/*']) # Authentication setting auth_settings = [] @@ -488,4 +493,5 @@ class FakeApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index b0aa2d9a842..d8c5eefc946 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -102,6 +102,7 @@ class PetApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -157,6 +158,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def delete_pet(self, pet_id, **kwargs): @@ -212,6 +214,7 @@ class PetApi(object): all_params = ['pet_id', 'api_key'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -269,6 +272,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def find_pets_by_status(self, status, **kwargs): @@ -322,6 +326,7 @@ class PetApi(object): all_params = ['status'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -378,6 +383,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def find_pets_by_tags(self, tags, **kwargs): @@ -431,6 +437,7 @@ class PetApi(object): all_params = ['tags'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -487,6 +494,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def get_pet_by_id(self, pet_id, **kwargs): @@ -540,6 +548,7 @@ class PetApi(object): all_params = ['pet_id'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -595,6 +604,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def update_pet(self, body, **kwargs): @@ -648,6 +658,7 @@ class PetApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -703,6 +714,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def update_pet_with_form(self, pet_id, **kwargs): @@ -760,6 +772,7 @@ class PetApi(object): all_params = ['pet_id', 'name', 'status'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -819,6 +832,7 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def upload_file(self, pet_id, **kwargs): @@ -876,6 +890,7 @@ class PetApi(object): all_params = ['pet_id', 'additional_metadata', 'file'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -935,4 +950,5 @@ class PetApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index c7f37de09e8..adcf8d2b4ed 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -102,6 +102,7 @@ class StoreApi(object): all_params = ['order_id'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -159,6 +160,7 @@ class StoreApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def get_inventory(self, **kwargs): @@ -210,6 +212,7 @@ class StoreApi(object): all_params = [] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -260,6 +263,7 @@ class StoreApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def get_order_by_id(self, order_id, **kwargs): @@ -313,6 +317,7 @@ class StoreApi(object): all_params = ['order_id'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -372,6 +377,7 @@ class StoreApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def place_order(self, body, **kwargs): @@ -425,6 +431,7 @@ class StoreApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -480,4 +487,5 @@ class StoreApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index cc7f2d35083..255b68a8c7f 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -102,6 +102,7 @@ class UserApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -157,6 +158,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def create_users_with_array_input(self, body, **kwargs): @@ -210,6 +212,7 @@ class UserApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -265,6 +268,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def create_users_with_list_input(self, body, **kwargs): @@ -318,6 +322,7 @@ class UserApi(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -373,6 +378,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def delete_user(self, username, **kwargs): @@ -426,6 +432,7 @@ class UserApi(object): all_params = ['username'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -481,6 +488,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def get_user_by_name(self, username, **kwargs): @@ -534,6 +542,7 @@ class UserApi(object): all_params = ['username'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -589,6 +598,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def login_user(self, username, password, **kwargs): @@ -644,6 +654,7 @@ class UserApi(object): all_params = ['username', 'password'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -704,6 +715,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def logout_user(self, **kwargs): @@ -755,6 +767,7 @@ class UserApi(object): all_params = [] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -805,6 +818,7 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) def update_user(self, username, body, **kwargs): @@ -860,6 +874,7 @@ class UserApi(object): all_params = ['username', 'body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') params = locals() for key, val in iteritems(params['kwargs']): @@ -920,4 +935,5 @@ class UserApi(object): auth_settings=auth_settings, callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index f8a4457ebae..c61b29c8120 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -105,7 +105,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None): + body=None, post_params=None, _preload_content=True): """ :param method: http request method :param url: http request url @@ -115,6 +115,8 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] @@ -141,11 +143,13 @@ class RESTClientObject(object): request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, + preload_content=_preload_content, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type @@ -154,6 +158,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=True, + preload_content=_preload_content, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided @@ -162,6 +167,7 @@ class RESTClientObject(object): request_body = body r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, headers=headers) else: # Cannot generate the request from given parameters @@ -172,68 +178,77 @@ class RESTClientObject(object): else: r = self.pool_manager.request(method, url, fields=query_params, + preload_content=_preload_content, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - r = RESTResponse(r) + if _preload_content: + r = RESTResponse(r) - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if PY3: - r.data = r.data.decode('utf8') + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if PY3: + r.data = r.data.decode('utf8') - # log response body - logger.debug("response body: %s", r.data) + # log response body + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) return r - def GET(self, url, headers=None, query_params=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True): return self.request("GET", url, headers=headers, + _preload_content=_preload_content, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True): return self.request("HEAD", url, headers=headers, + _preload_content=_preload_content, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None): + def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True): return self.request("DELETE", url, headers=headers, query_params=query_params, + _preload_content=_preload_content, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, body=body) From cfd8add825a80ac5ea264e2ac902fec064763215 Mon Sep 17 00:00:00 2001 From: mbohlool Date: Thu, 10 Nov 2016 14:24:06 -0800 Subject: [PATCH 046/269] Add test for _preload_content flag --- .../petstore/python/tests/test_pet_api.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 33c6d86c14a..a539d2c598f 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -45,6 +45,26 @@ class PetApiTests(unittest.TestCase): self.test_file_dir = os.path.realpath(self.test_file_dir) self.foo = os.path.join(self.test_file_dir, "foo.png") + def test_preload_content_flag(self): + self.pet_api.add_pet(body=self.pet) + + resp = self.pet_api.find_pets_by_status(status=[self.pet.status], _preload_content=False) + + # return response should at least have read and close methods. + self.assertTrue(hasattr(resp, 'read')) + self.assertTrue(hasattr(resp, 'close')) + + # Also we need to make sure we can release the connection to a pool (if exists) when we are done with it. + self.assertTrue(hasattr(resp, 'release_conn')) + + # Right now, the client returns urllib3.HTTPResponse. If that changed in future, it is probably a breaking + # change, however supporting above methods should be enough for most usecases. Remove this test case if + # we followed the breaking change procedure for python client (e.g. increasing major version). + self.assertTrue(resp.__class__, 'urllib3.response.HTTPResponse') + + resp.close() + resp.release_conn() + def test_create_api_instance(self): pet_api = petstore_api.PetApi() pet_api2 = petstore_api.PetApi() From f6a02f43393ad239db75de097c592c33a9b636f3 Mon Sep 17 00:00:00 2001 From: Chakrit Wichian Date: Fri, 11 Nov 2016 16:39:45 +0700 Subject: [PATCH 047/269] [ruby] Make sure super is always called for ApiError class. (#4168) * [ruby] Make sure super is always called for ApiError class. * Add test for Petstore::ApiError --- .../src/main/resources/ruby/api_error.mustache | 12 +++++++----- .../petstore/ruby/lib/petstore/api_error.rb | 12 +++++++----- .../client/petstore/ruby/spec/api_error_spec.rb | 15 +++++++++++++++ 3 files changed, 29 insertions(+), 10 deletions(-) create mode 100644 samples/client/petstore/ruby/spec/api_error_spec.rb diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache index ddd8cda32f5..b3320779b36 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache @@ -13,12 +13,14 @@ module {{moduleName}} # ApiError.new(:code => 404, :message => "Not Found") def initialize(arg = nil) if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + arg.each do |k, v| - if k.to_s == 'message' - super v - else - instance_variable_set "@#{k}", v - end + instance_variable_set "@#{k}", v end else super arg diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index aaf331230d3..30b03841f57 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -32,12 +32,14 @@ module Petstore # ApiError.new(:code => 404, :message => "Not Found") def initialize(arg = nil) if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + arg.each do |k, v| - if k.to_s == 'message' - super v - else - instance_variable_set "@#{k}", v - end + instance_variable_set "@#{k}", v end else super arg diff --git a/samples/client/petstore/ruby/spec/api_error_spec.rb b/samples/client/petstore/ruby/spec/api_error_spec.rb new file mode 100644 index 00000000000..1ea0ecd6817 --- /dev/null +++ b/samples/client/petstore/ruby/spec/api_error_spec.rb @@ -0,0 +1,15 @@ +require File.dirname(__FILE__) + '/spec_helper' + +describe Petstore::ApiClient do + describe '#initialize' do + it "should save the message if one is given" do + err = Petstore::ApiError.new(message: "Hello") + expect(err.message).to eq("Hello") + end + + it "should save the hash as message if no message is given" do + err = Petstore::ApiError.new(code: 500, response_body: "server error") + expect(err.message).to eq("{:code=>500, :response_body=>\"server error\"}") + end + end +end From 876669cd316c91f9629f08622341ed5c91f945b2 Mon Sep 17 00:00:00 2001 From: mbohlool Date: Fri, 11 Nov 2016 07:48:53 -0800 Subject: [PATCH 048/269] [Python] Add support for request timeout (#4173) * [Python] Add support for request timeout * Update python petstore api * [Python] Add test for request timeout --- .../src/main/resources/python/api.mustache | 2 + .../main/resources/python/api_client.mustache | 29 ++++++++--- .../src/main/resources/python/rest.mustache | 41 ++++++++++++--- .../python/petstore_api/api_client.py | 29 ++++++++--- .../python/petstore_api/apis/fake_api.py | 6 +++ .../python/petstore_api/apis/pet_api.py | 16 ++++++ .../python/petstore_api/apis/store_api.py | 8 +++ .../python/petstore_api/apis/user_api.py | 16 ++++++ .../petstore/python/petstore_api/rest.py | 41 ++++++++++++--- .../petstore/python/tests/test_pet_api.py | 52 +++++++++++++++++++ 10 files changed, 208 insertions(+), 32 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index c6a07b2f7a2..e3c687f7bad 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -99,6 +99,7 @@ class {{classname}}(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -213,6 +214,7 @@ class {{classname}}(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 11646705495..94046a878f5 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -96,7 +96,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): # header parameters header_params = header_params or {} @@ -144,7 +145,9 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, _preload_content=_preload_content) + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -279,7 +282,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -303,21 +307,23 @@ class ApiClient(object): :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: If provide parameter callback, the request will be called asynchronously. The method will return the request thread. If parameter callback is None, then the method will return the response directly. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. """ if callback is None: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats, _preload_content) + _return_http_data_only, collection_formats, _preload_content, _request_timeout) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -326,12 +332,12 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats, _preload_content)) + collection_formats, _preload_content, _request_timeout)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True): + post_params=None, body=None, _preload_content=True, _request_timeout=None): """ Makes the HTTP request using RESTClient. """ @@ -339,11 +345,13 @@ class ApiClient(object): return self.rest_client.GET(url, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, @@ -351,6 +359,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "POST": return self.rest_client.POST(url, @@ -358,6 +367,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, @@ -365,6 +375,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, @@ -372,12 +383,14 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) else: raise ValueError( diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 3f0e3dca292..8ddd17c473c 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -85,7 +85,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True): + body=None, post_params=None, _preload_content=True, _request_timeout=None): """ :param method: http request method :param url: http request url @@ -97,6 +97,8 @@ class RESTClientObject(object): and `multipart/form-data` :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] @@ -109,6 +111,13 @@ class RESTClientObject(object): post_params = post_params or {} headers = headers or {} + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + timeout = urllib3.Timeout(total=_request_timeout) + elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: + timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -124,12 +133,14 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, body=request_body, preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type @@ -139,6 +150,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, preload_content=_preload_content, + timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided @@ -148,6 +160,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, body=request_body, preload_content=_preload_content, + timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters @@ -159,6 +172,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, fields=query_params, preload_content=_preload_content, + timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) @@ -180,55 +194,66 @@ class RESTClientObject(object): return r - def GET(self, url, headers=None, query_params=None, _preload_content=True): + def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True): + def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index f13cb3772ad..16841117b1b 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -96,7 +96,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): # header parameters header_params = header_params or {} @@ -144,7 +145,9 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, _preload_content=_preload_content) + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data @@ -279,7 +282,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None, _preload_content=True): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -303,21 +307,23 @@ class ApiClient(object): :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: If provide parameter callback, the request will be called asynchronously. The method will return the request thread. If parameter callback is None, then the method will return the response directly. - :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without - reading/decoding response data. Default is True. """ if callback is None: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats, _preload_content) + _return_http_data_only, collection_formats, _preload_content, _request_timeout) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -326,12 +332,12 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats, _preload_content)) + collection_formats, _preload_content, _request_timeout)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True): + post_params=None, body=None, _preload_content=True, _request_timeout=None): """ Makes the HTTP request using RESTClient. """ @@ -339,11 +345,13 @@ class ApiClient(object): return self.rest_client.GET(url, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, @@ -351,6 +359,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "POST": return self.rest_client.POST(url, @@ -358,6 +367,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, @@ -365,6 +375,7 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, @@ -372,12 +383,14 @@ class ApiClient(object): headers=headers, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) else: raise ValueError( diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index cdf79483bc9..44eb2a07e43 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -103,6 +103,7 @@ class FakeApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -159,6 +160,7 @@ class FakeApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): @@ -239,6 +241,7 @@ class FakeApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -356,6 +359,7 @@ class FakeApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def test_enum_parameters(self, **kwargs): @@ -424,6 +428,7 @@ class FakeApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -494,4 +499,5 @@ class FakeApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index d8c5eefc946..431b4deb39a 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -103,6 +103,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -159,6 +160,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_pet(self, pet_id, **kwargs): @@ -215,6 +217,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -273,6 +276,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def find_pets_by_status(self, status, **kwargs): @@ -327,6 +331,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -384,6 +389,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def find_pets_by_tags(self, tags, **kwargs): @@ -438,6 +444,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -495,6 +502,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_pet_by_id(self, pet_id, **kwargs): @@ -549,6 +557,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -605,6 +614,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_pet(self, body, **kwargs): @@ -659,6 +669,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -715,6 +726,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_pet_with_form(self, pet_id, **kwargs): @@ -773,6 +785,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -833,6 +846,7 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def upload_file(self, pet_id, **kwargs): @@ -891,6 +905,7 @@ class PetApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -951,4 +966,5 @@ class PetApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index adcf8d2b4ed..55a916ef18a 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -103,6 +103,7 @@ class StoreApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -161,6 +162,7 @@ class StoreApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_inventory(self, **kwargs): @@ -213,6 +215,7 @@ class StoreApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -264,6 +267,7 @@ class StoreApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_order_by_id(self, order_id, **kwargs): @@ -318,6 +322,7 @@ class StoreApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -378,6 +383,7 @@ class StoreApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def place_order(self, body, **kwargs): @@ -432,6 +438,7 @@ class StoreApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -488,4 +495,5 @@ class StoreApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index 255b68a8c7f..6d23713217d 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -103,6 +103,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -159,6 +160,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def create_users_with_array_input(self, body, **kwargs): @@ -213,6 +215,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -269,6 +272,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def create_users_with_list_input(self, body, **kwargs): @@ -323,6 +327,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -379,6 +384,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_user(self, username, **kwargs): @@ -433,6 +439,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -489,6 +496,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_user_by_name(self, username, **kwargs): @@ -543,6 +551,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -599,6 +608,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def login_user(self, username, password, **kwargs): @@ -655,6 +665,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -716,6 +727,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def logout_user(self, **kwargs): @@ -768,6 +780,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -819,6 +832,7 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def update_user(self, username, body, **kwargs): @@ -875,6 +889,7 @@ class UserApi(object): all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -936,4 +951,5 @@ class UserApi(object): callback=params.get('callback'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index c61b29c8120..3a98beec9b1 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -105,7 +105,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True): + body=None, post_params=None, _preload_content=True, _request_timeout=None): """ :param method: http request method :param url: http request url @@ -117,6 +117,8 @@ class RESTClientObject(object): and `multipart/form-data` :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] @@ -129,6 +131,13 @@ class RESTClientObject(object): post_params = post_params or {} headers = headers or {} + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + timeout = urllib3.Timeout(total=_request_timeout) + elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: + timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -144,12 +153,14 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, body=request_body, preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type @@ -159,6 +170,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, preload_content=_preload_content, + timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided @@ -168,6 +180,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, body=request_body, preload_content=_preload_content, + timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters @@ -179,6 +192,7 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, fields=query_params, preload_content=_preload_content, + timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) @@ -200,55 +214,66 @@ class RESTClientObject(object): return r - def GET(self, url, headers=None, query_params=None, _preload_content=True): + def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None, _preload_content=True): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True): + def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index a539d2c598f..613b665cf5f 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -15,8 +15,38 @@ from petstore_api.rest import ApiException from .util import id_gen +import json + +import urllib3 + HOST = 'http://petstore.swagger.io/v2' + +class TimeoutWithEqual(urllib3.Timeout): + def __init__(self, *arg, **kwargs): + super(TimeoutWithEqual, self).__init__(*arg, **kwargs) + + def __eq__(self, other): + return self._read == other._read and self._connect == other._connect and self.total == other.total + + +class MockPoolManager(object): + def __init__(self, tc): + self._tc = tc + self._reqs = [] + + def expect_request(self, *args, **kwargs): + self._reqs.append((args, kwargs)) + + def request(self, *args, **kwargs): + self._tc.assertTrue(len(self._reqs)>0) + r = self._reqs.pop(0) + self._tc.maxDiff = None + self._tc.assertEqual(r[0], args) + self._tc.assertEqual(r[1], kwargs) + return urllib3.HTTPResponse(status=200, body=b'test') + + class PetApiTests(unittest.TestCase): def setUp(self): @@ -65,6 +95,28 @@ class PetApiTests(unittest.TestCase): resp.close() resp.release_conn() + def test_timeout(self): + mock_pool = MockPoolManager(self) + self.api_client.rest_client.pool_manager = mock_pool + + mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': 'application/json', + 'Authorization': 'Bearer ', + 'Accept': 'application/json', + 'User-Agent': 'Swagger-Codegen/1.0.0/python'}, + preload_content=True, timeout=TimeoutWithEqual(total=5)) + mock_pool.expect_request('POST', 'http://petstore.swagger.io/v2/pet', + body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)), + headers={'Content-Type': 'application/json', + 'Authorization': 'Bearer ', + 'Accept': 'application/json', + 'User-Agent': 'Swagger-Codegen/1.0.0/python'}, + preload_content=True, timeout=TimeoutWithEqual(connect=1, read=2)) + + self.pet_api.add_pet(body=self.pet, _request_timeout=5) + self.pet_api.add_pet(body=self.pet, _request_timeout=(1, 2)) + def test_create_api_instance(self): pet_api = petstore_api.PetApi() pet_api2 = petstore_api.PetApi() From 265d635eee1805745d22d71a6726aaea272e8113 Mon Sep 17 00:00:00 2001 From: Brian Shamblen Date: Fri, 11 Nov 2016 11:41:08 -0800 Subject: [PATCH 049/269] Add markdown support to descriptions --- .../main/resources/htmlDocs2/index.mustache | 148 ++++++++++-------- .../htmlDocs2/js_jsonschemaview.mustache | 4 +- .../main/resources/htmlDocs2/marked.mustache | 8 + 3 files changed, 91 insertions(+), 69 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/marked.mustache diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index c65ca350268..d8de13e9e76 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -12,70 +12,84 @@ {{>js_prettify}} {{>js_bootstrap}} +{{>marked}} - - + + -
+
-
- + {{#apiInfo}} + {{#apis}} + {{#operations}} + + {{#operation}} +
  • + {{nickname}} +
  • + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} + + +
    +
    +
    +
    +

    {{{appName}}}

    +
    +
    -
    -
    -
    -

    {{{appName}}}

    -
    -
    -
    - -
    - - {{#apiInfo}} - - {{#apis}} - {{#operations}} -
    -

    {{baseName}}

    - {{#operation}} - - - - - - - -
    - -
    -
    -

    {{nickname}}

    -

    {{summary}}

    -
    -
    - -
    -
    - -

    -

    {{notes}}

    -

    -
    - -
    {{path}}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    -
    -
    -
    -
    - -
    -
    
    -{{>sample_java}}
    -                                                  
    + - - - - - -

    Parameters

    - - - - {{#hasPathParams}} -
    Path parameters
    - - - - - - - {{#pathParams}} - {{>param}} - {{/pathParams}} -
    NameDescription
    - {{/hasPathParams}} - - {{#hasHeaderParams}} -
    Header parameters
    - - - - - - - {{#headerParams}} - {{>param}} - {{/headerParams}} - -
    NameDescription
    - {{/hasHeaderParams}} - - - {{#hasBodyParam}} -
    Body parameters
    - - - - - - - {{#bodyParams}} - {{>paramB}} - {{/bodyParams}} - -
    NameDescription
    - {{/hasBodyParam}} - - {{#hasFormParams}} -
    Form parameters
    - - - - - - - {{#formParams}} - {{>param}} - {{/formParams}} - -
    NameDescription
    - {{/hasFormParams}} - - {{#hasQueryParams}} -
    Query parameters
    - - - - - - - {{#queryParams}} - {{>param}} - {{/queryParams}} -
    NameDescription
    - {{/hasQueryParams}} - -

    Responses

    - {{#responses}} - -

    Status: {{code}} - {{message}}

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - {{#examples}} -
    -
    {{example}}
    -
    - {{/examples}} - - -
    - - - - {{/responses}} - - - - - - -
    - -
    - -
    - - {{/operation}} -
    - - {{/operations}} - {{/apis}} - - {{/apiInfo}} - - - - -
    - - - - - - - -
    -
    - Generated {{generatedDate}} -
    -
    +
    + {{#apiInfo}} + {{#apis}} + {{#operations}} +
    +

    {{baseName}}

    + {{#operation}} +
    +
    +
    +

    {{nickname}}

    +

    {{summary}}

    +
    +
    +
    +

    +

    {{notes}}

    +

    +
    +
    {{path}}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    +  
    +
    +
    +
    
    +  {{>sample_java}}
    +                            
    +
    + +
    +
    
    +  {{>sample_android}}
    +                            
    +
    + +
    +
    
    +  {{>sample_objc}}
    +                              
    +
    + +
    +
    
    +  {{>sample_js}}
    +                              
    +
    + + +
    +
    
    +  {{>sample_csharp}}
    +                              
    +
    + +
    +
    
    +  {{>sample_php}}
    +                              
    +
    +
    + +

    Parameters

    + + {{#hasPathParams}} +
    Path parameters
    + + + + + + {{#pathParams}} + {{>param}} + {{/pathParams}} +
    NameDescription
    + {{/hasPathParams}} + + {{#hasHeaderParams}} +
    Header parameters
    + + + + + + {{#headerParams}} + {{>param}} + {{/headerParams}} +
    NameDescription
    + {{/hasHeaderParams}} + + {{#hasBodyParam}} +
    Body parameters
    + + + + + + {{#bodyParams}} + {{>paramB}} + {{/bodyParams}} +
    NameDescription
    + {{/hasBodyParam}} + + {{#hasFormParams}} +
    Form parameters
    + + + + + + {{#formParams}} + {{>param}} + {{/formParams}} +
    NameDescription
    + {{/hasFormParams}} + + {{#hasQueryParams}} +
    Query parameters
    + + + + + + {{#queryParams}} + {{>param}} + {{/queryParams}} +
    NameDescription
    + {{/hasQueryParams}} + +

    Responses

    + {{#responses}} +

    Status: {{code}} - {{message}}

    + + {{#schema}} + + +
    +
    +
    + + +
    + +
    + {{#examples}} +
    +
    {{example}}
    +
    + {{/examples}} +
    + {{/schema}} + {{/responses}} +
    +
    +
    + {{/operation}} +
    + {{/operations}} + {{/apis}} + {{/apiInfo}} +
    + +
    +
    + Generated {{generatedDate}} +
    +
    +
    -
    - - - - - - -{{>js_jsonschemaview}} -{{>js_jsonref}} -{{>js_webfontloader}} - - - - - +
    + {{>js_jsonschemaview}} + {{>js_jsonref}} + {{>js_webfontloader}} + - diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache index 173ea07a044..d299d5fd13d 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/js_jsonschemaview.mustache @@ -251,10 +251,10 @@ var JSONSchemaView = (function () { } if (this.schema['enum']) { - var formatter = new JSONFormatter(this.schema['enum'], this.open - 1); - var formatterEl = formatter.render(); - formatterEl.classList.add('inner'); - element.querySelector('.enums.inner').appendChild(formatterEl); + var tempDiv = document.createElement('span');; + tempDiv.classList.add('inner'); + tempDiv.innerHTML = '' + this.schema['enum'].join(', ') + ''; + element.querySelector('.enums.inner').appendChild(tempDiv); } if (this.isArray) { diff --git a/samples/html2/index.html b/samples/html2/index.html index a4de731cfb6..d7ee2cea468 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -6,17 +6,14 @@ - - - - - - - + - - - - + -
    +
    - +
    +
    +
    +

    Swagger Petstore

    +
    +
    -
    -
    -
    -

    Swagger Petstore

    -
    -
    -
    - -
    +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    petId*
    + + + + + -
    NameDescription
    petId* @@ -1704,16 +1497,15 @@ try {
    + -
    Header parameters
    - - - - - - - +
    Header parameters
    +
    NameDescription
    apiKey
    + + + + + - -
    NameDescription
    apiKey @@ -1745,174 +1537,54 @@ try {
    - - - - - -

    Responses

    - -

    Status: 400 - Invalid pet value

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - -
    - -
    - - - - - - - - -
    - -
    -
    -

    findPetsByStatus

    -

    Finds Pets by status

    -
    -
    - -
    -
    - -

    -

    Multiple status values can be provided with comma separated strings

    -

    -
    - -
    /pet/findByStatus
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +
    +                          

    Responses

    +

    Status: 400 - Invalid pet value

    + +
    +
    +
    +
    +
    +
    +

    findPetsByStatus

    +

    Finds Pets by status

    +
    +
    +
    +

    +

    Multiple status values can be provided with comma separated strings

    +

    +
    +
    /pet/findByStatus
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -1941,13 +1613,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -1964,18 +1635,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    @@ -1996,11 +1664,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
    @@ -2021,16 +1690,15 @@ var callback = function(error, data, response) {
     };
     api.findPetsByStatus(status, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -2063,13 +1731,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  findPetsByStatus: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    +
    -
    +

    Parameters

    -

    Parameters

    - - - - - - - - -
    Query parameters
    - - - - - - - +
    Query parameters
    +
    NameDescription
    status*
    + + + + + -
    NameDescription
    status* @@ -2149,41 +1807,25 @@ try {
    + -

    Responses

    +

    Responses

    +

    Status: 200 - successful operation

    -

    Status: 200 - successful operation

    + - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid status value

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - -
    - -
    - - - - - - - - -
    - -
    -
    -

    findPetsByTags

    -

    Finds Pets by tags

    -
    -
    - -
    -
    - -

    -

    Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.

    -

    -
    - -
    /pet/findByTags
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-Pet-findPetsByStatus-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-Pet-findPetsByStatus-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid status value

    + + + +
    +
    +
    +
    +

    findPetsByTags

    +

    Finds Pets by tags

    +
    +
    +
    +

    +

    Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.

    +

    +
    +
    /pet/findByTags
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -2422,13 +1925,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -2445,18 +1947,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    @@ -2477,11 +1976,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
    @@ -2502,16 +2002,15 @@ var callback = function(error, data, response) {
     };
     api.findPetsByTags(tags, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -2544,13 +2043,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  findPetsByTags: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    -

    Parameters

    - - - - - - - - -
    Query parameters
    - - - - - - - +
    Query parameters
    +
    NameDescription
    tags*
    + + + + + -
    NameDescription
    tags* @@ -2628,41 +2117,25 @@ try {
    + -

    Responses

    +

    Responses

    +

    Status: 200 - successful operation

    -

    Status: 200 - successful operation

    + - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid tag value

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    getPetById

    -

    Find pet by ID

    -
    -
    - -
    -
    - -

    -

    Returns a single pet

    -

    -
    - -
    /pet/{petId}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-Pet-findPetsByTags-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-Pet-findPetsByTags-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid tag value

    + + + +
    +
    +
    +
    +

    getPetById

    +

    Find pet by ID

    +
    +
    +
    +

    +

    Returns a single pet

    +

    +
    +
    /pet/{petId}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -2903,13 +2237,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -2926,18 +2259,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure API key authorization: (authentication scheme: api_key)
     [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
    @@ -2960,11 +2290,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure API key authorization: api_key
    @@ -2987,16 +2318,15 @@ var callback = function(error, data, response) {
     };
     api.getPetById(petId, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -3031,13 +2361,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  getPetById: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    petId*
    + + + + + -
    NameDescription
    petId* @@ -3109,329 +2430,99 @@ try {
    + +

    Responses

    +

    Status: 200 - successful operation

    -

    Responses

    + - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid ID supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - Pet not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    updatePet

    -

    Update an existing pet

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /pet
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X put "http://petstore.swagger.io/v2/pet"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-Pet-getPetById-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-Pet-getPetById-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid ID supplied

    + +

    Status: 404 - Pet not found

    + + + +
    +
    +
    +
    +

    updatePet

    +

    Update an existing pet

    +
    +
    +
    +

    +

    +

    +
    +
    /pet
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X put "http://petstore.swagger.io/v2/pet"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -3459,13 +2550,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -3481,18 +2571,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    @@ -3510,11 +2597,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
    @@ -3535,16 +2623,15 @@ var callback = function(error, data, response) {
     };
     api.updatePet(body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -3576,13 +2663,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  updatePet: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - -

    Parameters

    - - - - - - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -3664,324 +2741,57 @@ try {
    - - - -

    Responses

    - -

    Status: 400 - Invalid ID supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - Pet not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 405 - Validation exception

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    updatePetWithForm

    -

    Updates a pet in the store with form data

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /pet/{petId}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +                          

    Responses

    +

    Status: 400 - Invalid ID supplied

    + +

    Status: 404 - Pet not found

    + +

    Status: 405 - Validation exception

    + +
    +
    +
    +
    +
    +
    +

    updatePetWithForm

    +

    Updates a pet in the store with form data

    +
    +
    +
    +

    +

    +

    +
    +
    /pet/{petId}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -4011,13 +2821,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -4035,18 +2844,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    @@ -4068,11 +2874,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
    @@ -4097,16 +2904,15 @@ var callback = function(error, data, response) {
     };
     api.updatePetWithForm(petId, opts, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -4140,13 +2946,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  updatePetWithForm: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    petId*
    + + + + + -
    NameDescription
    petId* @@ -4217,19 +3014,17 @@ try {
    + - -
    Form parameters
    - - - - - - - +
    Form parameters
    +
    NameDescription
    name
    + + + + + - + - -
    NameDescription
    name @@ -4262,7 +3057,7 @@ try {
    status
    status @@ -4295,171 +3090,52 @@ try {
    - - -

    Responses

    - -

    Status: 405 - Invalid input

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    uploadFile

    -

    uploads an image

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /pet/{petId}/uploadImage
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +                          

    Responses

    +

    Status: 405 - Invalid input

    + +
    +
    +
    +
    +
    +
    +

    uploadFile

    +

    uploads an image

    +
    +
    +
    +

    +

    +

    +
    +
    /pet/{petId}/uploadImage
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .PetApi;
    @@ -4490,13 +3166,12 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .PetApi;
    +                          
    +
    
    +  import .PetApi;
     
     public class PetApiExample {
     
    @@ -4515,18 +3190,15 @@ public class PetApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
    @@ -4551,11 +3223,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
    @@ -4580,16 +3253,15 @@ var callback = function(error, data, response) {
     };
     api.uploadFile(petId, opts, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -4624,13 +3296,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  uploadFile: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    petId*
    + + + + + -
    NameDescription
    petId* @@ -4702,19 +3365,17 @@ try {
    + - -
    Form parameters
    - - - - - - - +
    Form parameters
    +
    NameDescription
    additionalMetadata
    + + + + + - + - -
    NameDescription
    additionalMetadata @@ -4747,7 +3408,7 @@ try {
    file
    file @@ -4780,178 +3441,95 @@ try {
    + -

    Responses

    +

    Responses

    +

    Status: 200 - successful operation

    -

    Status: 200 - successful operation

    + - - - - - - - -
    - - - -
    - - - - -
    - - +
    + +
    +
    + + +
    + +
    +

    Store

    +
    +
    +
    +

    deleteOrder

    +

    Delete purchase order by ID

    +
    +
    +
    +

    +

    For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

    +

    +
    +
    /store/order/{orderId}
    +

    +

    Usage and SDK Samples

    +

    + - //console.log(JSON.stringify(resolved)); - - - - var view = new JSONSchemaView(resolved.schema, 3); - $('#examples-Pet-uploadFile-schema-data').val(JSON.stringify(resolved.schema)); - var result = $('#examples-Pet-uploadFile-schema-200'); - result.empty(); - result.append(view.render()); - }); - - - - - }); - -
    - - - - - - - - - - - - - - - - - - - - - - - - - - -
    - -
    - -
    -

    Store

    - - - - - - - -
    - -
    -
    -

    deleteOrder

    -

    Delete purchase order by ID

    -
    -
    - -
    -
    - -

    -

    For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

    -

    -
    - -
    /store/order/{orderId}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                        
    +
    +
    
    +  curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .StoreApi;
    @@ -4974,13 +3552,12 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .StoreApi;
    +                          
    +
    
    +  import .StoreApi;
     
     public class StoreApiExample {
     
    @@ -4996,18 +3573,15 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     String *orderId = orderId_example; // ID of the order that needs to be deleted
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
    @@ -5020,11 +3594,12 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .StoreApi()
     
    @@ -5040,16 +3615,15 @@ var callback = function(error, data, response) {
     };
     api.deleteOrder(orderId, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -5078,13 +3652,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  deleteOrder: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    +
    - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    orderId*
    + + + + + -
    NameDescription
    orderId* @@ -5150,250 +3715,57 @@ try {
    - - - - - - -

    Responses

    - -

    Status: 400 - Invalid ID supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - Order not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    getInventory

    -

    Returns pet inventories by status

    -
    -
    - -
    -
    - -

    -

    Returns a map of status codes to quantities

    -

    -
    - -
    /store/inventory
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +
    +
    +                          

    Responses

    +

    Status: 400 - Invalid ID supplied

    + +

    Status: 404 - Order not found

    + +
    +
    +
    +
    +
    +
    +

    getInventory

    +

    Returns pet inventories by status

    +
    +
    +
    +

    +

    Returns a map of status codes to quantities

    +

    +
    +
    /store/inventory
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .StoreApi;
    @@ -5423,13 +3795,12 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .StoreApi;
    +                          
    +
    
    +  import .StoreApi;
     
     public class StoreApiExample {
     
    @@ -5445,18 +3816,15 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -Configuration *apiConfig = [Configuration sharedConfig];
    +                            
    +
    + +
    +
    
    +  Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure API key authorization: (authentication scheme: api_key)
     [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
    @@ -5478,11 +3846,12 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     var defaultClient = .ApiClient.instance;
     
     // Configure API key authorization: api_key
    @@ -5502,16 +3871,15 @@ var callback = function(error, data, response) {
     };
     api.getInventory(callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -5545,13 +3913,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  getInventory: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - - - - - - -

    Parameters

    +

    Parameters

    +

    Responses

    +

    Status: 200 - successful operation

    + -

    Responses

    +
    +
    +
    -

    Status: 200 - successful operation

    - - - - - - - - - -
    - - - -
    - - - - -
    - - +
    + +
    +
    + +
    +
    +
    +
    +
    +

    getOrderById

    +

    Find purchase order by ID

    +
    +
    +
    +

    +

    For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions

    +

    +
    +
    /store/order/{orderId}
    +

    +

    Usage and SDK Samples

    +

    + - //console.log(JSON.stringify(resolved)); - - - - var view = new JSONSchemaView(resolved.schema, 3); - $('#examples-Store-getInventory-schema-data').val(JSON.stringify(resolved.schema)); - var result = $('#examples-Store-getInventory-schema-200'); - result.empty(); - result.append(view.render()); - }); - - - - - }); - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    getOrderById

    -

    Find purchase order by ID

    -
    -
    - -
    -
    - -

    -

    For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions

    -

    -
    - -
    /store/order/{orderId}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                        
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .StoreApi;
    @@ -5778,13 +4056,12 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .StoreApi;
    +                          
    +
    
    +  import .StoreApi;
     
     public class StoreApiExample {
     
    @@ -5801,18 +4078,15 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     Long *orderId = 789; // ID of pet that needs to be fetched
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
    @@ -5828,11 +4102,12 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .StoreApi()
     
    @@ -5848,16 +4123,15 @@ var callback = function(error, data, response) {
     };
     api.getOrderById(orderId, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -5887,13 +4161,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  getOrderById: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    +
    - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    orderId*
    + + + + + -
    NameDescription
    orderId* @@ -5962,329 +4227,99 @@ try {
    + +

    Responses

    +

    Status: 200 - successful operation

    -

    Responses

    + - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid ID supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - Order not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    placeOrder

    -

    Place an order for a pet

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /store/order
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/store/order"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-Store-getOrderById-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-Store-getOrderById-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid ID supplied

    + +

    Status: 404 - Order not found

    + + + +
    +
    +
    +
    +

    placeOrder

    +

    Place an order for a pet

    +
    +
    +
    +

    +

    +

    +
    +
    /store/order
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/store/order"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .StoreApi;
    @@ -6308,13 +4343,12 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .StoreApi;
    +                          
    +
    
    +  import .StoreApi;
     
     public class StoreApiExample {
     
    @@ -6331,18 +4365,15 @@ public class StoreApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     Order *body = ; // order placed for purchasing the pet
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
    @@ -6358,11 +4389,12 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .StoreApi()
     
    @@ -6378,16 +4410,15 @@ var callback = function(error, data, response) {
     };
     api.placeOrder(body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -6417,13 +4448,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  placeOrder: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - -

    Parameters

    - - - - - - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -6503,255 +4524,98 @@ try {
    + -

    Responses

    +

    Responses

    +

    Status: 200 - successful operation

    -

    Status: 200 - successful operation

    + - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid Order

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - -
    - -
    -

    User

    - - - - - - - -
    - -
    -
    -

    createUser

    -

    Create user

    -
    -
    - -
    -
    - -

    -

    This can only be done by the logged in user.

    -

    -
    - -
    /user
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/user"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-Store-placeOrder-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-Store-placeOrder-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid Order

    + + + +
    +
    +
    +

    User

    +
    +
    +
    +

    createUser

    +

    Create user

    +
    +
    +
    +

    +

    This can only be done by the logged in user.

    +

    +
    +
    /user
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/user"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -6774,13 +4638,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -6796,18 +4659,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     User *body = ; // Created user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -6820,11 +4680,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -6840,16 +4701,15 @@ var callback = function(error, data, response) {
     };
     api.createUser(body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -6878,13 +4738,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  createUser: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - -

    Parameters

    - - - - - - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -6963,172 +4813,53 @@ try {
    - - - -

    Responses

    - -

    Status: 0 - successful operation

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    createUsersWithArrayInput

    -

    Creates list of users with given input array

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /user/createWithArray
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +                          

    Responses

    +

    Status: 0 - successful operation

    + +
    +
    +
    +
    +
    +
    +

    createUsersWithArrayInput

    +

    Creates list of users with given input array

    +
    +
    +
    +

    +

    +

    +
    +
    /user/createWithArray
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -7151,13 +4882,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -7173,18 +4903,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     array[User] *body = ; // List of user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -7197,11 +4924,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -7217,16 +4945,15 @@ var callback = function(error, data, response) {
     };
     api.createUsersWithArrayInput(body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -7255,13 +4982,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - -

    Parameters

    - - - - - - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -7343,172 +5060,53 @@ try {
    - - - -

    Responses

    - -

    Status: 0 - successful operation

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    createUsersWithListInput

    -

    Creates list of users with given input array

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /user/createWithList
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X post "http://petstore.swagger.io/v2/user/createWithList"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +                          

    Responses

    +

    Status: 0 - successful operation

    + +
    +
    +
    +
    +
    +
    +

    createUsersWithListInput

    +

    Creates list of users with given input array

    +
    +
    +
    +

    +

    +

    +
    +
    /user/createWithList
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X post "http://petstore.swagger.io/v2/user/createWithList"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -7531,13 +5129,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -7553,18 +5150,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     array[User] *body = ; // List of user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -7577,11 +5171,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -7597,16 +5192,15 @@ var callback = function(error, data, response) {
     };
     api.createUsersWithListInput(body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -7635,13 +5229,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  createUsersWithListInput: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - -

    Parameters

    - - - - - - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -7723,172 +5307,53 @@ try {
    - - - -

    Responses

    - -

    Status: 0 - successful operation

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    deleteUser

    -

    Delete user

    -
    -
    - -
    -
    - -

    -

    This can only be done by the logged in user.

    -

    -
    - -
    /user/{username}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X delete "http://petstore.swagger.io/v2/user/{username}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +                          

    Responses

    +

    Status: 0 - successful operation

    + +
    +
    +
    +
    +
    +
    +

    deleteUser

    +

    Delete user

    +
    +
    +
    +

    +

    This can only be done by the logged in user.

    +

    +
    +
    /user/{username}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X delete "http://petstore.swagger.io/v2/user/{username}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -7911,13 +5376,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -7933,18 +5397,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     String *username = username_example; // The name that needs to be deleted
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -7957,11 +5418,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -7977,16 +5439,15 @@ var callback = function(error, data, response) {
     };
     api.deleteUser(username, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -8015,13 +5476,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  deleteUser: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    username*
    + + + + + -
    NameDescription
    username* @@ -8086,250 +5538,57 @@ try {
    - - - - - - -

    Responses

    - -

    Status: 400 - Invalid username supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - User not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    getUserByName

    -

    Get user by user name

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /user/{username}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/user/{username}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                            
    +
    +
    +
    +
    +
    +                          

    Responses

    +

    Status: 400 - Invalid username supplied

    + +

    Status: 404 - User not found

    + +
    +
    +
    +
    +
    +
    +

    getUserByName

    +

    Get user by user name

    +
    +
    +
    +

    +

    +

    +
    +
    /user/{username}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/user/{username}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -8353,13 +5612,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -8376,18 +5634,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     String *username = username_example; // The name that needs to be fetched. Use user1 for testing. 
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -8403,11 +5658,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -8423,16 +5679,15 @@ var callback = function(error, data, response) {
     };
     api.getUserByName(username, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -8462,13 +5717,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  getUserByName: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    username*
    + + + + + -
    NameDescription
    username* @@ -8534,329 +5780,99 @@ try {
    + +

    Responses

    +

    Status: 200 - successful operation

    -

    Responses

    + - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid username supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - User not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    loginUser

    -

    Logs user into the system

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /user/login
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-User-getUserByName-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-User-getUserByName-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid username supplied

    + +

    Status: 404 - User not found

    + + + +
    +
    +
    +
    +

    loginUser

    +

    Logs user into the system

    +
    +
    +
    +

    +

    +

    +
    +
    /user/login
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -8881,13 +5897,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -8905,18 +5920,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     String *username = username_example; // The user name for login
     String *password = password_example; // The password for login in clear text
     
    @@ -8934,11 +5946,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -8956,16 +5969,15 @@ var callback = function(error, data, response) {
     };
     api.loginUser(username, password, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -8996,13 +6008,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  loginUser: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    -

    Parameters

    - - - - - - - - -
    Query parameters
    - - - - - - - +
    Query parameters
    +
    NameDescription
    username*
    + + + + + - + -
    NameDescription
    username* @@ -9074,7 +6076,7 @@ try {
    password*
    password* @@ -9107,41 +6109,25 @@ try {
    + -

    Responses

    +

    Responses

    +

    Status: 200 - successful operation

    -

    Status: 200 - successful operation

    + - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 400 - Invalid username/password supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    logoutUser

    -

    Logs out current logged in user session

    -
    -
    - -
    -
    - -

    -

    -

    -
    - -
    /user/logout
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X get "http://petstore.swagger.io/v2/user/logout"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                                        var schema = schemaWrapper.schema;
    +                                        schemaWrapper.definitions = defs;
    +                                        //console.log(JSON.stringify(schema))
    +                                        JsonRefs.resolveRefs(schemaWrapper, {
    +                                            "depth": 3,
    +                                            "resolveRemoteRefs": false,
    +                                            "resolveFileRefs": false
    +                                        }, function(err, resolved, metadata) {
    +                                          //console.log(JSON.stringify(resolved));
    +                                          var view = new JSONSchemaView(resolved.schema, 3);
    +                                          $('#examples-User-loginUser-schema-data').val(JSON.stringify(resolved.schema));
    +                                          var result = $('#examples-User-loginUser-schema-200');
    +                                          result.empty();
    +                                          result.append(view.render());
    +                                        });
    +                                      });
    +                                    
    +                                  
    + +
    +
    +

    Status: 400 - Invalid username/password supplied

    + + + +
    +
    +
    +
    +

    logoutUser

    +

    Logs out current logged in user session

    +
    +
    +
    +

    +

    +

    +
    +
    /user/logout
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X get "http://petstore.swagger.io/v2/user/logout"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -9382,13 +6229,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -9403,18 +6249,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -9426,11 +6269,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -9443,16 +6287,15 @@ var callback = function(error, data, response) {
     };
     api.logoutUser(callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -9480,13 +6323,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  logoutUser: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    - -
    - - - - - -

    Parameters

    - - - - - - - - - -

    Responses

    - -

    Status: 0 - successful operation

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - - - - - - - - -
    - -
    -
    -

    updateUser

    -

    Updated user

    -
    -
    - -
    -
    - -

    -

    This can only be done by the logged in user.

    -

    -
    - -
    /user/{username}
    - -

    -

    Usage and SDK Samples

    -

    - - - -
    -
    -
    
    -curl -X put "http://petstore.swagger.io/v2/user/{username}"
    -
    -
    -
    -
    - -
    -
    
    -import io.swagger.client.*;
    +                              
    +
    +
    + +

    Parameters

    + + + + + + +

    Responses

    +

    Status: 0 - successful operation

    + +
    +
    +
    +
    +
    +
    +

    updateUser

    +

    Updated user

    +
    +
    +
    +

    +

    This can only be done by the logged in user.

    +

    +
    +
    /user/{username}
    +

    +

    Usage and SDK Samples

    +

    + + +
    +
    +
    
    +  curl -X put "http://petstore.swagger.io/v2/user/{username}"
    +  
    +
    +
    +
    
    +  import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
     import .UserApi;
    @@ -9700,13 +6416,12 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    +
    +
    - -
    -
    
    -import .UserApi;
    +                          
    +
    
    +  import .UserApi;
     
     public class UserApiExample {
     
    @@ -9723,18 +6438,15 @@ public class UserApiExample {
         }
     }
     
    -                                                  
    -
    - - - - -
    -
    
    -
    +                            
    +
    + +
    +
    
    +  
     String *username = username_example; // name that need to be deleted
     User *body = ; // Updated user object
     
    @@ -9749,11 +6461,12 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                 }
                             }];
     
    -                                                    
    -
    -
    -
    
    -var  = require('');
    +                              
    +
    + +
    +
    
    +  var  = require('');
     
     var api = new .UserApi()
     
    @@ -9771,16 +6484,15 @@ var callback = function(error, data, response) {
     };
     api.updateUser(username, body, callback);
     
    -                                                    
    -
    +
    +
    - - -
    -
    
    -using System;
    +                            
    +                            
    +
    
    +  using System;
     using System.Diagnostics;
     using .Api;
     using .Client;
    @@ -9810,13 +6522,12 @@ namespace Example
         }
     }
     
    -                                                    
    -
    +
    +
    - -
    -
    
    -
    +                              
    
    +  updateUser: ', $e->getMessage(), PHP_EOL;
     }
     
    -                                                  
    -
    + +
    + - +

    Parameters

    - - - - -

    Parameters

    - - - -
    Path parameters
    - - - - - - - +
    Path parameters
    +
    NameDescription
    username*
    + + + + + -
    NameDescription
    username* @@ -9882,18 +6585,16 @@ try {
    + - -
    Body parameters
    - - - - - - - +
    Body parameters
    +
    NameDescription
    body *
    + + + + + - -
    NameDescription
    body * @@ -9937,214 +6638,38 @@ try {
    - - - -

    Responses

    - -

    Status: 400 - Invalid user supplied

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - -

    Status: 404 - User not found

    - - - - - - - - - -
    - - - -
    - - - - -
    - - -
    - - - - - - - -
    - - - - -
    - - - - - - - - - - - - - -
    - -
    - + +

    Responses

    +

    Status: 400 - Invalid user supplied

    +

    Status: 404 - User not found

    + + +
    + + + + - - - - - - - - - - - - - - - + - From d548a8078c2b021ea924f008119c22b5e8c5c983 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 17 Nov 2016 21:49:57 +0800 Subject: [PATCH 066/269] add taskdata --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 26c247a2ec0..a934a3c3cec 100644 --- a/README.md +++ b/README.md @@ -804,6 +804,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) +- [TaskData](http://www.taskdata.com/) - [ThoughtWorks](https://www.thoughtworks.com) - [uShip](https://www.uship.com/) - [W.UP](http://wup.hu/?siteLang=en) From e5daa6855c86de4644397e659c0d0497b267f681 Mon Sep 17 00:00:00 2001 From: cbornet Date: Sun, 13 Nov 2016 20:20:28 +0100 Subject: [PATCH 067/269] add models support to flask --- bin/flaskConnexion-python2.sh | 3 +- bin/flaskConnexion.sh | 3 +- .../io/swagger/codegen/DefaultCodegen.java | 3 + .../languages/FlaskConnexionCodegen.java | 217 ++++++++++++++- .../resources/flaskConnexion/README.mustache | 2 +- ..._.mustache => __init__controller.mustache} | 0 .../flaskConnexion/__init__model.mustache | 6 + .../resources/flaskConnexion/app.mustache | 21 ++ .../flaskConnexion/base_model_.mustache | 79 ++++++ .../flaskConnexion/controller.mustache | 100 ++++++- .../resources/flaskConnexion/model.mustache | 148 +++++++++++ .../flaskConnexion/param_type.mustache | 1 + .../resources/flaskConnexion/util.mustache | 149 +++++++++++ .../petstore/flaskConnexion-python2/README.md | 2 +- .../petstore/flaskConnexion-python2/app.py | 21 ++ .../controllers/pet_controller.py | 99 ++++++- .../controllers/store_controller.py | 42 +++ .../controllers/user_controller.py | 88 +++++++ .../flaskConnexion-python2/models/__init__.py | 10 + .../models/api_response.py | 116 ++++++++ .../models/base_model_.py | 72 +++++ .../flaskConnexion-python2/models/category.py | 90 +++++++ .../flaskConnexion-python2/models/order.py | 202 ++++++++++++++ .../flaskConnexion-python2/models/pet.py | 208 +++++++++++++++ .../flaskConnexion-python2/models/tag.py | 90 +++++++ .../flaskConnexion-python2/models/user.py | 248 ++++++++++++++++++ .../swagger/swagger.yaml | 10 +- .../petstore/flaskConnexion-python2/util.py | 149 +++++++++++ samples/server/petstore/flaskConnexion/app.py | 21 ++ .../flaskConnexion/controllers/init.py | 0 .../controllers/pet_controller.py | 109 +++++++- .../controllers/store_controller.py | 50 +++- .../controllers/user_controller.py | 104 +++++++- .../server/petstore/flaskConnexion/init.py | 0 .../flaskConnexion/models/__init__.py | 10 + .../flaskConnexion/models/api_response.py | 116 ++++++++ .../flaskConnexion/models/base_model_.py | 75 ++++++ .../flaskConnexion/models/category.py | 90 +++++++ .../petstore/flaskConnexion/models/order.py | 202 ++++++++++++++ .../petstore/flaskConnexion/models/pet.py | 208 +++++++++++++++ .../petstore/flaskConnexion/models/tag.py | 90 +++++++ .../petstore/flaskConnexion/models/user.py | 248 ++++++++++++++++++ .../flaskConnexion/swagger/swagger.yaml | 10 +- .../server/petstore/flaskConnexion/util.py | 149 +++++++++++ 44 files changed, 3615 insertions(+), 46 deletions(-) rename modules/swagger-codegen/src/main/resources/flaskConnexion/{__init__.mustache => __init__controller.mustache} (100%) create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/param_type.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache create mode 100644 samples/server/petstore/flaskConnexion-python2/models/__init__.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/api_response.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/base_model_.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/category.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/order.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/pet.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/tag.py create mode 100644 samples/server/petstore/flaskConnexion-python2/models/user.py create mode 100644 samples/server/petstore/flaskConnexion-python2/util.py delete mode 100644 samples/server/petstore/flaskConnexion/controllers/init.py delete mode 100644 samples/server/petstore/flaskConnexion/init.py create mode 100644 samples/server/petstore/flaskConnexion/models/__init__.py create mode 100644 samples/server/petstore/flaskConnexion/models/api_response.py create mode 100644 samples/server/petstore/flaskConnexion/models/base_model_.py create mode 100644 samples/server/petstore/flaskConnexion/models/category.py create mode 100644 samples/server/petstore/flaskConnexion/models/order.py create mode 100644 samples/server/petstore/flaskConnexion/models/pet.py create mode 100644 samples/server/petstore/flaskConnexion/models/tag.py create mode 100644 samples/server/petstore/flaskConnexion/models/user.py create mode 100644 samples/server/petstore/flaskConnexion/util.py diff --git a/bin/flaskConnexion-python2.sh b/bin/flaskConnexion-python2.sh index 313ef297bf8..579e6d94be2 100755 --- a/bin/flaskConnexion-python2.sh +++ b/bin/flaskConnexion-python2.sh @@ -27,6 +27,7 @@ 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.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -DsupportPython2=true" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -c bin/supportPython2.json" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/flaskConnexion -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion-python2 -c bin/supportPython2.json" +rm -rf samples/server/petstore/flaskConnexion-python2/* java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/flaskConnexion.sh b/bin/flaskConnexion.sh index 563718f9061..c09c83b2daa 100755 --- a/bin/flaskConnexion.sh +++ b/bin/flaskConnexion.sh @@ -26,6 +26,7 @@ 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.yaml -l python-flask -o samples/server/petstore/flaskConnexion " +ags="$@ generate -t modules/swagger-codegen/src/main/resources/flaskConnexion -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l python-flask -o samples/server/petstore/flaskConnexion " +rm -rf samples/server/petstore/flaskConnexion/* java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 63cad401d02..5ccc9b24945 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2234,6 +2234,7 @@ public class DefaultCodegen { collectionFormat = "csv"; } CodegenProperty pr = fromProperty("inner", inner); + p.items = pr; p.baseType = pr.datatype; p.isContainer = true; p.isListContainer = true; @@ -2247,6 +2248,7 @@ public class DefaultCodegen { property = new MapProperty(inner); collectionFormat = qp.getCollectionFormat(); CodegenProperty pr = fromProperty("inner", inner); + p.items = pr; p.baseType = pr.datatype; p.isContainer = true; p.isMapContainer = true; @@ -2360,6 +2362,7 @@ public class DefaultCodegen { imports.add(cp.complexType); } imports.add(cp.baseType); + p.items = cp; p.dataType = cp.datatype; p.baseType = cp.complexType; p.isPrimitiveType = cp.isPrimitiveType; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 2ac51c7e9e1..63e3f3c3705 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -5,17 +5,18 @@ import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; -import config.ConfigParser; import io.swagger.codegen.*; import io.swagger.models.HttpMethod; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; +import io.swagger.models.properties.*; import io.swagger.util.Yaml; import java.io.File; import java.util.*; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,11 +40,13 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("List"); + languageSpecificPrimitives.add("Dict"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("datetime"); languageSpecificPrimitives.add("date"); + languageSpecificPrimitives.add("file"); typeMapping.clear(); typeMapping.put("integer", "int"); @@ -51,8 +54,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf typeMapping.put("number", "float"); typeMapping.put("long", "int"); typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "dict"); + typeMapping.put("array", "List"); + typeMapping.put("map", "Dict"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "str"); typeMapping.put("date", "date"); @@ -63,9 +66,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf // set the output folder here outputFolder = "generated-code/connexion"; - modelTemplateFiles.clear(); - apiTemplateFiles.put("controller.mustache", ".py"); + modelTemplateFiles.put("model.mustache", ".py"); /* * Template Location. This is the location which templates will be read from. The generator @@ -102,11 +104,15 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf "", "app.py") ); + supportingFiles.add(new SupportingFile("util.mustache", + "", + "util.py") + ); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") ); - supportingFiles.add(new SupportingFile("__init__.mustache", + supportingFiles.add(new SupportingFile("__init__controller.mustache", "", "__init__.py") ); @@ -142,14 +148,29 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) { additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE); + typeMapping.put("long", "long"); } if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) { - supportingFiles.add(new SupportingFile("__init__.mustache", + supportingFiles.add(new SupportingFile("__init__controller.mustache", controllerPackage, "__init__.py") ); } + + supportingFiles.add(new SupportingFile("__init__model.mustache", + modelPackage, + "__init__.py") + ); + + supportingFiles.add(new SupportingFile("base_model_.mustache", + modelPackage, + "base_model_.py") + ); + } + + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); } @Override @@ -224,6 +245,36 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[str, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = toModelName(swaggerType); + } + return type; + } + @Override public void preprocessSwagger(Swagger swagger) { @@ -333,6 +384,96 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return super.postProcessSupportingFileData(objs); } + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // remove dollar sign + name = name.replaceAll("$", ""); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) { + name = name.toLowerCase(); + } + + // underscore the variable name + // petId => pet_id + name = underscore(name); + + // remove leading underscore + name = name.replaceAll("^_*", ""); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toModelFilename(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model filename. Renamed to " + underscore(dropDots("model_" + name))); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + underscore("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // underscore the model file name + // PhoneNumber => phone_number + return underscore(dropDots(name)); + } + + @Override + public String toModelName(String name) { + name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + // remove dollar sign + name = name.replaceAll("$", ""); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + @Override public String toOperationId(String operationId) { operationId = super.toOperationId(operationId); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. @@ -344,6 +485,56 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return underscore(operationId); } + /** + * Return the default value of the property + * + * @param p Swagger property object + * @return string presentation of the default value of the property + */ + @Override + public String toDefaultValue(Property p) { + if (p instanceof StringProperty) { + StringProperty dp = (StringProperty) p; + if (dp.getDefault() != null) { + return "'" + dp.getDefault() + "'"; + } + } else if (p instanceof BooleanProperty) { + BooleanProperty dp = (BooleanProperty) p; + if (dp.getDefault() != null) { + if (dp.getDefault().toString().equalsIgnoreCase("false")) + return "False"; + else + return "True"; + } + } else if (p instanceof DateProperty) { + // TODO + } else if (p instanceof DateTimeProperty) { + // TODO + } else if (p instanceof DoubleProperty) { + DoubleProperty dp = (DoubleProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof FloatProperty) { + FloatProperty dp = (FloatProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof IntegerProperty) { + IntegerProperty dp = (IntegerProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString(); + } + } + + return null; + } + @Override public String escapeQuotationMark(String input) { // remove ' to avoid code injection @@ -355,4 +546,14 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf // remove multiline comment return input.replace("'''", "'_'_'"); } + + @Override + public String toModelImport(String name) { + String modelImport = "from "; + if (!"".equals(modelPackage())) { + modelImport += modelPackage() + "."; + } + modelImport += toModelFilename(name)+ " import " + name; + return modelImport; + } } diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index d53139b49b2..e037cf1fe15 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -11,7 +11,7 @@ To run the server, please execute the following: ``` {{#supportPython2}} -sudo pip install -U connexion # install Connexion from PyPI +sudo pip install -U connexion typing # install Connexion and Typing from PyPI python app.py {{/supportPython2}} {{^supportPython2}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__controller.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/flaskConnexion/__init__.mustache rename to modules/swagger-codegen/src/main/resources/flaskConnexion/__init__controller.mustache diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache new file mode 100644 index 00000000000..764211e2120 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__model.mustache @@ -0,0 +1,6 @@ +# coding: utf-8 + +from __future__ import absolute_import +# import models into model package +{{#models}}{{#model}}from .{{classFilename}} import {{classname}}{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache index 85fd9a354f1..8428dedddaa 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache @@ -6,8 +6,29 @@ {{/supportPython2}} import connexion +from connexion.decorators import produces +from six import iteritems +from {{modelPackage}}.base_model_ import Model + + +class JSONEncoder(produces.JSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return produces.JSONEncoder.default(self, o) + if __name__ == '__main__': app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) app.run(port={{serverPort}}) diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache new file mode 100644 index 00000000000..ba7b5b23dc1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache @@ -0,0 +1,79 @@ +from pprint import pformat +{{^supportPython2}} +from typing import TypeVar, Type +{{/supportPython2}} +from six import iteritems +from util import deserialize_model +{{^supportPython2}} + +T = TypeVar('T') +{{/supportPython2}} + + +class Model(object): + # swaggerTypes: The key is attribute name and the value is attribute type. + swagger_types = {} + + # attributeMap: The key is attribute name and the value is json key in definition. + attribute_map = {} + + @classmethod + def from_dict(cls{{^supportPython2}}: Type[T]{{/supportPython2}}, dikt){{^supportPython2}} -> T{{/supportPython2}}: + """ + Returns the dict as a model + """ + return deserialize_model(dikt, cls) + + def to_dict(self): + """ + Returns the model properties as a dict + + :rtype: dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + + :rtype: str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache index 8050f04ba51..f762017284d 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -1,7 +1,105 @@ +import connexion +{{#imports}}{{import}} +{{/imports}} +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime {{#operations}} {{#operation}} -def {{operationId}}({{#allParams}}{{paramName}}{{^required}} = None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{^supportPython2}} -> str{{/supportPython2}}: + +def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}): + """ + {{#summary}}{{.}}{{/summary}}{{^summary}}{{operationId}}{{/summary}} + {{#notes}}{{.}}{{/notes}} + {{#allParams}} + :param {{paramName}}: {{description}} + {{^isContainer}} + {{#isPrimitiveType}} + :type {{paramName}}: {{>param_type}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isFile}} + :type {{paramName}}: werkzeug.datastructures.FileStorage + {{/isFile}} + {{^isFile}} + :type {{paramName}}: dict | bytes + {{/isFile}} + {{/isPrimitiveType}} + {{/isContainer}} + {{#isListContainer}} + {{#items}} + {{#isPrimitiveType}} + :type {{paramName}}: List[{{>param_type}}] + {{/isPrimitiveType}} + {{^isPrimitiveType}} + :type {{paramName}}: list | bytes + {{/isPrimitiveType}} + {{/items}} + {{/isListContainer}} + {{#isMapContainer}} + {{#items}} + {{#isPrimitiveType}} + :type {{paramName}}: Dict[str, {{>param_type}}] + {{/isPrimitiveType}} + {{^isPrimitiveType}} + :type {{paramName}}: dict | bytes + {{/isPrimitiveType}} + {{/items}} + {{/isMapContainer}} + {{/allParams}} + + :rtype: {{#returnType}}{{.}}{{/returnType}}{{^returnType}}None{{/returnType}} + """ + {{#allParams}} + {{^isContainer}} + {{#isDate}} + {{paramName}} = deserialize_date({{paramName}}) + {{/isDate}} + {{#isDateTime}} + {{paramName}} = deserialize_datetime({{paramName}}) + {{/isDateTime}} + {{^isPrimitiveType}} + {{^isFile}} + if connexion.request.is_json: + {{paramName}} = {{baseType}}.from_dict(connexion.request.get_json()) + {{/isFile}} + {{/isPrimitiveType}} + {{/isContainer}} + {{#isListContainer}} + {{#items}} + {{#isDate}} + if connexion.request.is_json: + {{paramName}} = [deserialize_date(s) for s in connexion.request.get_json()] + {{/isDate}} + {{#isDateTime}} + if connexion.request.is_json: + {{paramName}} = [deserialize_datetime(s) for s in connexion.request.get_json()] + {{/isDateTime}} + {{#complexType}} + if connexion.request.is_json: + {{paramName}} = [{{complexType}}.from_dict(d) for d in connexion.request.get_json()] + {{/complexType}} + {{/items}} + {{/isListContainer}} + {{#isMapContainer}} + {{#items}} + {{#isDate}} + if connexion.request.is_json: + {{paramName}} = {k: deserialize_date(v) for k, v in iteritems(connexion.request.get_json())} + {{/isDate}} + {{#isDateTime}} + if connexion.request.is_json: + {{paramName}} = {k: deserialize_datetime(v) for k, v in iteritems(connexion.request.get_json())} + {{/isDateTime}} + {{#complexType}} + if connexion.request.is_json: + {{paramName}} = {k: {{baseType}}.from_dict(v) for k, v in iteritems(connexion.request.get_json())} + {{/complexType}} + {{/items}} + {{/isMapContainer}} + {{/allParams}} return 'do some magic!' {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache new file mode 100644 index 00000000000..36b0af83c69 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache @@ -0,0 +1,148 @@ +# coding: utf-8 + +from __future__ import absolute_import +{{#imports}}{{import}} +{{/imports}} +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +{{#models}} +{{#model}} +class {{classname}}(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self{{#vars}}, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}={{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{/vars}}): + """ + {{classname}} - a model defined in Swagger + + {{#vars}} + :param {{name}}: The {{name}} of this {{classname}}. + :type {{name}}: {{datatype}} + {{/vars}} + """ + self.swagger_types = { + {{#vars}}'{{name}}': {{{datatype}}}{{#hasMore}}, + {{/hasMore}}{{/vars}} + } + + self.attribute_map = { + {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + } + +{{#vars}} + self._{{name}} = {{name}} +{{/vars}} + + @classmethod + def from_dict(cls, dikt){{^supportPython2}} -> '{{classname}}'{{/supportPython2}}: + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The {{name}} of this {{classname}}. + :rtype: {{classname}} + """ + return deserialize_model(dikt, cls) +{{#vars}}{{#-first}} +{{/-first}} + @property + def {{name}}(self){{^supportPython2}} -> {{datatype}}{{/supportPython2}}: + """ + Gets the {{name}} of this {{classname}}. + {{#description}} + {{{description}}} + {{/description}} + + :return: The {{name}} of this {{classname}}. + :rtype: {{datatype}} + """ + return self._{{name}} + + @{{name}}.setter + def {{name}}(self, {{name}}{{^supportPython2}}: {{datatype}}{{/supportPython2}}): + """ + Sets the {{name}} of this {{classname}}. + {{#description}} + {{{description}}} + {{/description}} + + :param {{name}}: The {{name}} of this {{classname}}. + :type {{name}}: {{datatype}} + """ +{{#isEnum}} + allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}] +{{#isContainer}} +{{#isListContainer}} + if not set({{{name}}}).issubset(set(allowed_values)): + raise ValueError( + "Invalid values for `{{{name}}}` [{0}], must be a subset of [{1}]" + .format(", ".join(map(str, set({{{name}}})-set(allowed_values))), + ", ".join(map(str, allowed_values))) + ) +{{/isListContainer}} +{{#isMapContainer}} + if not set({{{name}}}.keys()).issubset(set(allowed_values)): + raise ValueError( + "Invalid keys in `{{{name}}}` [{0}], must be a subset of [{1}]" + .format(", ".join(map(str, set({{{name}}}.keys())-set(allowed_values))), + ", ".join(map(str, allowed_values))) + ) +{{/isMapContainer}} +{{/isContainer}} +{{^isContainer}} + if {{{name}}} not in allowed_values: + raise ValueError( + "Invalid value for `{{{name}}}` ({0}), must be one of {1}" + .format({{{name}}}, allowed_values) + ) +{{/isContainer}} +{{/isEnum}} +{{^isEnum}} +{{#required}} + if {{name}} is None: + raise ValueError("Invalid value for `{{name}}`, must not be `None`") +{{/required}} +{{#hasValidation}} +{{#maxLength}} + if {{name}} is not None and len({{name}}) > {{maxLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be less than or equal to `{{maxLength}}`") +{{/maxLength}} +{{#minLength}} + if {{name}} is not None and len({{name}}) < {{minLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") +{{/minLength}} +{{#maximum}} + if {{name}} is not None and {{name}} >{{#exclusiveMaximum}}={{/exclusiveMaximum}} {{maximum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value less than {{^exclusiveMaximum}}or equal to {{/exclusiveMaximum}}`{{maximum}}`") +{{/maximum}} +{{#minimum}} + if {{name}} is not None and {{name}} <{{#exclusiveMinimum}}={{/exclusiveMinimum}} {{minimum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value greater than {{^exclusiveMinimum}}or equal to {{/exclusiveMinimum}}`{{minimum}}`") +{{/minimum}} +{{#pattern}} + if {{name}} is not None and not re.search('{{{vendorExtensions.x-regex}}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{{pattern}}}`") +{{/pattern}} +{{#maxItems}} + if {{name}} is not None and len({{name}}) > {{maxItems}}: + raise ValueError("Invalid value for `{{name}}`, number of items must be less than or equal to `{{maxItems}}`") +{{/maxItems}} +{{#minItems}} + if {{name}} is not None and len({{name}}) < {{minItems}}: + raise ValueError("Invalid value for `{{name}}`, number of items must be greater than or equal to `{{minItems}}`") +{{/minItems}} +{{/hasValidation}} +{{/isEnum}} + + self._{{name}} = {{name}} + +{{/vars}} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/param_type.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/param_type.mustache new file mode 100644 index 00000000000..21e7e07ec53 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/param_type.mustache @@ -0,0 +1 @@ +{{#isString}}str{{/isString}}{{#isInteger}}int{{/isInteger}}{{#isLong}}int{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}float{{/isDouble}}{{#isByteArray}}str{{/isByteArray}}{{#isBinary}}str{{/isBinary}}{{#isBoolean}}bool{{/isBoolean}}{{#isDate}}str{{/isDate}}{{#isDateTime}}str{{/isDateTime}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache new file mode 100644 index 00000000000..40c72d43ebd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/util.mustache @@ -0,0 +1,149 @@ +from typing import GenericMeta +from datetime import datetime, date +from six import integer_types, iteritems + + +def _deserialize(data, klass): + """ + Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if klass in integer_types or klass in (float, str, bool): + return _deserialize_primitive(data, klass) + elif klass == object: + return _deserialize_object(data) + elif klass == date: + return deserialize_date(data) + elif klass == datetime: + return deserialize_datetime(data) + elif type(klass) == GenericMeta: + if klass.__extra__ == list: + return _deserialize_list(data, klass.__args__[0]) + if klass.__extra__ == dict: + return _deserialize_dict(data, klass.__args__[1]) + else: + return deserialize_model(data, klass) + + +def _deserialize_primitive(data, klass): + """ + Deserializes to primitive type. + + :param data: data to deserialize. + :param klass: class literal. + + :return: int, long, float, str, bool. + :rtype: int | long | float | str | bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + +def _deserialize_object(value): + """ + Return a original value. + + :return: object. + """ + return value + + +def deserialize_date(string): + """ + Deserializes string to date. + + :param string: str. + :type string: str + :return: date. + :rtype: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + + +def deserialize_datetime(string): + """ + Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :type string: str + :return: datetime. + :rtype: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + + +def deserialize_model(data, klass): + """ + Deserializes list or dict to model. + + :param data: dict, list. + :type data: dict | list + :param klass: class literal. + :return: model object. + """ + instance = klass() + + if not instance.swagger_types: + return data + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data \ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, _deserialize(value, attr_type)) + + return instance + + +def _deserialize_list(data, boxed_type): + """ + Deserializes a list and its elements. + + :param data: list to deserialize. + :type data: list + :param boxed_type: class literal. + + :return: deserialized list. + :rtype: list + """ + return [_deserialize(sub_data, boxed_type) + for sub_data in data] + + + +def _deserialize_dict(data, boxed_type): + """ + Deserializes a dict and its elements. + + :param data: dict to deserialize. + :type data: dict + :param boxed_type: class literal. + + :return: deserialized dict. + :rtype: dict + """ + return {k: _deserialize(v, boxed_type) + for k, v in iteritems(data)} diff --git a/samples/server/petstore/flaskConnexion-python2/README.md b/samples/server/petstore/flaskConnexion-python2/README.md index cfc25505bd7..da392f1dd02 100644 --- a/samples/server/petstore/flaskConnexion-python2/README.md +++ b/samples/server/petstore/flaskConnexion-python2/README.md @@ -10,7 +10,7 @@ This example uses the [Connexion](https://github.com/zalando/connexion) library To run the server, please execute the following: ``` -sudo pip install -U connexion # install Connexion from PyPI +sudo pip install -U connexion typing # install Connexion and Typing from PyPI python app.py ``` diff --git a/samples/server/petstore/flaskConnexion-python2/app.py b/samples/server/petstore/flaskConnexion-python2/app.py index 47814427205..413af17ec79 100644 --- a/samples/server/petstore/flaskConnexion-python2/app.py +++ b/samples/server/petstore/flaskConnexion-python2/app.py @@ -1,8 +1,29 @@ #!/usr/bin/env python import connexion +from connexion.decorators import produces +from six import iteritems +from models.base_model_ import Model + + +class JSONEncoder(produces.JSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return produces.JSONEncoder.default(self, o) + if __name__ == '__main__': app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py index d58d3973ca2..461f6163a63 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py @@ -1,24 +1,117 @@ +import connexion +from models.pet import Pet +from models.api_response import ApiResponse +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime + def add_pet(body): + """ + Add a new pet to the store + + :param body: Pet object that needs to be added to the store + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = Pet.from_dict(connexion.request.get_json()) return 'do some magic!' -def delete_pet(petId, apiKey = None): + +def delete_pet(petId, apiKey=None): + """ + Deletes a pet + + :param petId: Pet id to delete + :type petId: int + :param apiKey: + :type apiKey: str + + :rtype: None + """ return 'do some magic!' + def find_pets_by_status(status): + """ + Finds Pets by status + Multiple status values can be provided with comma separated strings + :param status: Status values that need to be considered for filter + :type status: List[str] + + :rtype: List[Pet] + """ return 'do some magic!' + def find_pets_by_tags(tags): + """ + Finds Pets by tags + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + :param tags: Tags to filter by + :type tags: List[str] + + :rtype: List[Pet] + """ return 'do some magic!' + def get_pet_by_id(petId): + """ + Find pet by ID + Returns a single pet + :param petId: ID of pet to return + :type petId: int + + :rtype: Pet + """ return 'do some magic!' + def update_pet(body): + """ + Update an existing pet + + :param body: Pet object that needs to be added to the store + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = Pet.from_dict(connexion.request.get_json()) return 'do some magic!' -def update_pet_with_form(petId, name = None, status = None): + +def update_pet_with_form(petId, name=None, status=None): + """ + Updates a pet in the store with form data + + :param petId: ID of pet that needs to be updated + :type petId: int + :param name: Updated name of the pet + :type name: str + :param status: Updated status of the pet + :type status: str + + :rtype: None + """ return 'do some magic!' -def upload_file(petId, additionalMetadata = None, file = None): + +def upload_file(petId, additionalMetadata=None, file=None): + """ + uploads an image + + :param petId: ID of pet to update + :type petId: int + :param additionalMetadata: Additional data to pass to server + :type additionalMetadata: str + :param file: file to upload + :type file: werkzeug.datastructures.FileStorage + + :rtype: ApiResponse + """ return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py index a25eb40febb..5373cbf5f71 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py @@ -1,12 +1,54 @@ +import connexion +from models.order import Order +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime + def delete_order(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 + :type orderId: str + + :rtype: None + """ return 'do some magic!' + def get_inventory(): + """ + Returns pet inventories by status + Returns a map of status codes to quantities + + :rtype: Dict[str, int] + """ return 'do some magic!' + def get_order_by_id(orderId): + """ + 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 + :type orderId: int + + :rtype: Order + """ return 'do some magic!' + def place_order(body): + """ + Place an order for a pet + + :param body: order placed for purchasing the pet + :type body: dict | bytes + + :rtype: Order + """ + if connexion.request.is_json: + body = Order.from_dict(connexion.request.get_json()) return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py index ec4efef29eb..0e406488a7f 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py @@ -1,24 +1,112 @@ +import connexion +from models.user import User +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime + def create_user(body): + """ + Create user + This can only be done by the logged in user. + :param body: Created user object + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = User.from_dict(connexion.request.get_json()) return 'do some magic!' + def create_users_with_array_input(body): + """ + Creates list of users with given input array + + :param body: List of user object + :type body: list | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = [User.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!' + def create_users_with_list_input(body): + """ + Creates list of users with given input array + + :param body: List of user object + :type body: list | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = [User.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!' + def delete_user(username): + """ + Delete user + This can only be done by the logged in user. + :param username: The name that needs to be deleted + :type username: str + + :rtype: None + """ return 'do some magic!' + def get_user_by_name(username): + """ + Get user by user name + + :param username: The name that needs to be fetched. Use user1 for testing. + :type username: str + + :rtype: User + """ return 'do some magic!' + def login_user(username, password): + """ + Logs user into the system + + :param username: The user name for login + :type username: str + :param password: The password for login in clear text + :type password: str + + :rtype: str + """ return 'do some magic!' + def logout_user(): + """ + Logs out current logged in user session + + + :rtype: None + """ return 'do some magic!' + def update_user(username, body): + """ + Updated user + This can only be done by the logged in user. + :param username: name that need to be deleted + :type username: str + :param body: Updated user object + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = User.from_dict(connexion.request.get_json()) return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion-python2/models/__init__.py b/samples/server/petstore/flaskConnexion-python2/models/__init__.py new file mode 100644 index 00000000000..6571ad28e0f --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/__init__.py @@ -0,0 +1,10 @@ +# coding: utf-8 + +from __future__ import absolute_import +# import models into model package +from .api_response import ApiResponse +from .category import Category +from .order import Order +from .pet import Pet +from .tag import Tag +from .user import User diff --git a/samples/server/petstore/flaskConnexion-python2/models/api_response.py b/samples/server/petstore/flaskConnexion-python2/models/api_response.py new file mode 100644 index 00000000000..aeeee173602 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/api_response.py @@ -0,0 +1,116 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class ApiResponse(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, code=None, type=None, message=None): + """ + ApiResponse - a model defined in Swagger + + :param code: The code of this ApiResponse. + :type code: int + :param type: The type of this ApiResponse. + :type type: str + :param message: The message of this ApiResponse. + :type message: str + """ + self.swagger_types = { + 'code': int, + 'type': str, + 'message': str + } + + self.attribute_map = { + 'code': 'code', + 'type': 'type', + 'message': 'message' + } + + self._code = code + self._type = type + self._message = message + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The ApiResponse of this ApiResponse. + :rtype: ApiResponse + """ + return deserialize_model(dikt, cls) + + @property + def code(self): + """ + Gets the code of this ApiResponse. + + :return: The code of this ApiResponse. + :rtype: int + """ + return self._code + + @code.setter + def code(self, code): + """ + Sets the code of this ApiResponse. + + :param code: The code of this ApiResponse. + :type code: int + """ + + self._code = code + + @property + def type(self): + """ + Gets the type of this ApiResponse. + + :return: The type of this ApiResponse. + :rtype: str + """ + return self._type + + @type.setter + def type(self, type): + """ + Sets the type of this ApiResponse. + + :param type: The type of this ApiResponse. + :type type: str + """ + + self._type = type + + @property + def message(self): + """ + Gets the message of this ApiResponse. + + :return: The message of this ApiResponse. + :rtype: str + """ + return self._message + + @message.setter + def message(self, message): + """ + Sets the message of this ApiResponse. + + :param message: The message of this ApiResponse. + :type message: str + """ + + self._message = message + diff --git a/samples/server/petstore/flaskConnexion-python2/models/base_model_.py b/samples/server/petstore/flaskConnexion-python2/models/base_model_.py new file mode 100644 index 00000000000..61136d40eff --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/base_model_.py @@ -0,0 +1,72 @@ +from pprint import pformat +from six import iteritems +from util import deserialize_model + + +class Model(object): + # swaggerTypes: The key is attribute name and the value is attribute type. + swagger_types = {} + + # attributeMap: The key is attribute name and the value is json key in definition. + attribute_map = {} + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + """ + return deserialize_model(dikt, cls) + + def to_dict(self): + """ + Returns the model properties as a dict + + :rtype: dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + + :rtype: str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion-python2/models/category.py b/samples/server/petstore/flaskConnexion-python2/models/category.py new file mode 100644 index 00000000000..82fd59fe337 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/category.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Category(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id=None, name=None): + """ + Category - a model defined in Swagger + + :param id: The id of this Category. + :type id: int + :param name: The name of this Category. + :type name: str + """ + self.swagger_types = { + 'id': int, + 'name': str + } + + self.attribute_map = { + 'id': 'id', + 'name': 'name' + } + + self._id = id + self._name = name + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Category of this Category. + :rtype: Category + """ + return deserialize_model(dikt, cls) + + @property + def id(self): + """ + Gets the id of this Category. + + :return: The id of this Category. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Category. + + :param id: The id of this Category. + :type id: int + """ + + self._id = id + + @property + def name(self): + """ + Gets the name of this Category. + + :return: The name of this Category. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Category. + + :param name: The name of this Category. + :type name: str + """ + + self._name = name + diff --git a/samples/server/petstore/flaskConnexion-python2/models/order.py b/samples/server/petstore/flaskConnexion-python2/models/order.py new file mode 100644 index 00000000000..20c6fbe4102 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/order.py @@ -0,0 +1,202 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Order(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): + """ + Order - a model defined in Swagger + + :param id: The id of this Order. + :type id: int + :param pet_id: The pet_id of this Order. + :type pet_id: int + :param quantity: The quantity of this Order. + :type quantity: int + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + :param status: The status of this Order. + :type status: str + :param complete: The complete of this Order. + :type complete: bool + """ + self.swagger_types = { + 'id': int, + 'pet_id': int, + 'quantity': int, + 'ship_date': datetime, + 'status': str, + 'complete': bool + } + + self.attribute_map = { + 'id': 'id', + 'pet_id': 'petId', + 'quantity': 'quantity', + 'ship_date': 'shipDate', + 'status': 'status', + 'complete': 'complete' + } + + self._id = id + self._pet_id = pet_id + self._quantity = quantity + self._ship_date = ship_date + self._status = status + self._complete = complete + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Order of this Order. + :rtype: Order + """ + return deserialize_model(dikt, cls) + + @property + def id(self): + """ + Gets the id of this Order. + + :return: The id of this Order. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Order. + + :param id: The id of this Order. + :type id: int + """ + + self._id = id + + @property + def pet_id(self): + """ + Gets the pet_id of this Order. + + :return: The pet_id of this Order. + :rtype: int + """ + return self._pet_id + + @pet_id.setter + def pet_id(self, pet_id): + """ + Sets the pet_id of this Order. + + :param pet_id: The pet_id of this Order. + :type pet_id: int + """ + + self._pet_id = pet_id + + @property + def quantity(self): + """ + Gets the quantity of this Order. + + :return: The quantity of this Order. + :rtype: int + """ + return self._quantity + + @quantity.setter + def quantity(self, quantity): + """ + Sets the quantity of this Order. + + :param quantity: The quantity of this Order. + :type quantity: int + """ + + self._quantity = quantity + + @property + def ship_date(self): + """ + Gets the ship_date of this Order. + + :return: The ship_date of this Order. + :rtype: datetime + """ + return self._ship_date + + @ship_date.setter + def ship_date(self, ship_date): + """ + Sets the ship_date of this Order. + + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + """ + + self._ship_date = ship_date + + @property + def status(self): + """ + Gets the status of this Order. + Order Status + + :return: The status of this Order. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """ + Sets the status of this Order. + Order Status + + :param status: The status of this Order. + :type status: str + """ + allowed_values = ["placed", "approved", "delivered"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) + ) + + self._status = status + + @property + def complete(self): + """ + Gets the complete of this Order. + + :return: The complete of this Order. + :rtype: bool + """ + return self._complete + + @complete.setter + def complete(self, complete): + """ + Sets the complete of this Order. + + :param complete: The complete of this Order. + :type complete: bool + """ + + self._complete = complete + diff --git a/samples/server/petstore/flaskConnexion-python2/models/pet.py b/samples/server/petstore/flaskConnexion-python2/models/pet.py new file mode 100644 index 00000000000..5bd32865fbd --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/pet.py @@ -0,0 +1,208 @@ +# coding: utf-8 + +from __future__ import absolute_import +from models.category import Category +from models.tag import Tag +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Pet(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): + """ + Pet - a model defined in Swagger + + :param id: The id of this Pet. + :type id: int + :param category: The category of this Pet. + :type category: Category + :param name: The name of this Pet. + :type name: str + :param photo_urls: The photo_urls of this Pet. + :type photo_urls: List[str] + :param tags: The tags of this Pet. + :type tags: List[Tag] + :param status: The status of this Pet. + :type status: str + """ + self.swagger_types = { + 'id': int, + 'category': Category, + 'name': str, + 'photo_urls': List[str], + 'tags': List[Tag], + 'status': str + } + + self.attribute_map = { + 'id': 'id', + 'category': 'category', + 'name': 'name', + 'photo_urls': 'photoUrls', + 'tags': 'tags', + 'status': 'status' + } + + self._id = id + self._category = category + self._name = name + self._photo_urls = photo_urls + self._tags = tags + self._status = status + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Pet of this Pet. + :rtype: Pet + """ + return deserialize_model(dikt, cls) + + @property + def id(self): + """ + Gets the id of this Pet. + + :return: The id of this Pet. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Pet. + + :param id: The id of this Pet. + :type id: int + """ + + self._id = id + + @property + def category(self): + """ + Gets the category of this Pet. + + :return: The category of this Pet. + :rtype: Category + """ + return self._category + + @category.setter + def category(self, category): + """ + Sets the category of this Pet. + + :param category: The category of this Pet. + :type category: Category + """ + + self._category = category + + @property + def name(self): + """ + Gets the name of this Pet. + + :return: The name of this Pet. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Pet. + + :param name: The name of this Pet. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") + + self._name = name + + @property + def photo_urls(self): + """ + Gets the photo_urls of this Pet. + + :return: The photo_urls of this Pet. + :rtype: List[str] + """ + return self._photo_urls + + @photo_urls.setter + def photo_urls(self, photo_urls): + """ + Sets the photo_urls of this Pet. + + :param photo_urls: The photo_urls of this Pet. + :type photo_urls: List[str] + """ + if photo_urls is None: + raise ValueError("Invalid value for `photo_urls`, must not be `None`") + + self._photo_urls = photo_urls + + @property + def tags(self): + """ + Gets the tags of this Pet. + + :return: The tags of this Pet. + :rtype: List[Tag] + """ + return self._tags + + @tags.setter + def tags(self, tags): + """ + Sets the tags of this Pet. + + :param tags: The tags of this Pet. + :type tags: List[Tag] + """ + + self._tags = tags + + @property + def status(self): + """ + Gets the status of this Pet. + pet status in the store + + :return: The status of this Pet. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status): + """ + Sets the status of this Pet. + pet status in the store + + :param status: The status of this Pet. + :type status: str + """ + allowed_values = ["available", "pending", "sold"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) + ) + + self._status = status + diff --git a/samples/server/petstore/flaskConnexion-python2/models/tag.py b/samples/server/petstore/flaskConnexion-python2/models/tag.py new file mode 100644 index 00000000000..e397ac90255 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/tag.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Tag(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id=None, name=None): + """ + Tag - a model defined in Swagger + + :param id: The id of this Tag. + :type id: int + :param name: The name of this Tag. + :type name: str + """ + self.swagger_types = { + 'id': int, + 'name': str + } + + self.attribute_map = { + 'id': 'id', + 'name': 'name' + } + + self._id = id + self._name = name + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Tag of this Tag. + :rtype: Tag + """ + return deserialize_model(dikt, cls) + + @property + def id(self): + """ + Gets the id of this Tag. + + :return: The id of this Tag. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this Tag. + + :param id: The id of this Tag. + :type id: int + """ + + self._id = id + + @property + def name(self): + """ + Gets the name of this Tag. + + :return: The name of this Tag. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name): + """ + Sets the name of this Tag. + + :param name: The name of this Tag. + :type name: str + """ + + self._name = name + diff --git a/samples/server/petstore/flaskConnexion-python2/models/user.py b/samples/server/petstore/flaskConnexion-python2/models/user.py new file mode 100644 index 00000000000..134dfd7a892 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/models/user.py @@ -0,0 +1,248 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class User(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): + """ + User - a model defined in Swagger + + :param id: The id of this User. + :type id: int + :param username: The username of this User. + :type username: str + :param first_name: The first_name of this User. + :type first_name: str + :param last_name: The last_name of this User. + :type last_name: str + :param email: The email of this User. + :type email: str + :param password: The password of this User. + :type password: str + :param phone: The phone of this User. + :type phone: str + :param user_status: The user_status of this User. + :type user_status: int + """ + self.swagger_types = { + 'id': int, + 'username': str, + 'first_name': str, + 'last_name': str, + 'email': str, + 'password': str, + 'phone': str, + 'user_status': int + } + + self.attribute_map = { + 'id': 'id', + 'username': 'username', + 'first_name': 'firstName', + 'last_name': 'lastName', + 'email': 'email', + 'password': 'password', + 'phone': 'phone', + 'user_status': 'userStatus' + } + + self._id = id + self._username = username + self._first_name = first_name + self._last_name = last_name + self._email = email + self._password = password + self._phone = phone + self._user_status = user_status + + @classmethod + def from_dict(cls, dikt): + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The User of this User. + :rtype: User + """ + return deserialize_model(dikt, cls) + + @property + def id(self): + """ + Gets the id of this User. + + :return: The id of this User. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id): + """ + Sets the id of this User. + + :param id: The id of this User. + :type id: int + """ + + self._id = id + + @property + def username(self): + """ + Gets the username of this User. + + :return: The username of this User. + :rtype: str + """ + return self._username + + @username.setter + def username(self, username): + """ + Sets the username of this User. + + :param username: The username of this User. + :type username: str + """ + + self._username = username + + @property + def first_name(self): + """ + Gets the first_name of this User. + + :return: The first_name of this User. + :rtype: str + """ + return self._first_name + + @first_name.setter + def first_name(self, first_name): + """ + Sets the first_name of this User. + + :param first_name: The first_name of this User. + :type first_name: str + """ + + self._first_name = first_name + + @property + def last_name(self): + """ + Gets the last_name of this User. + + :return: The last_name of this User. + :rtype: str + """ + return self._last_name + + @last_name.setter + def last_name(self, last_name): + """ + Sets the last_name of this User. + + :param last_name: The last_name of this User. + :type last_name: str + """ + + self._last_name = last_name + + @property + def email(self): + """ + Gets the email of this User. + + :return: The email of this User. + :rtype: str + """ + return self._email + + @email.setter + def email(self, email): + """ + Sets the email of this User. + + :param email: The email of this User. + :type email: str + """ + + self._email = email + + @property + def password(self): + """ + Gets the password of this User. + + :return: The password of this User. + :rtype: str + """ + return self._password + + @password.setter + def password(self, password): + """ + Sets the password of this User. + + :param password: The password of this User. + :type password: str + """ + + self._password = password + + @property + def phone(self): + """ + Gets the phone of this User. + + :return: The phone of this User. + :rtype: str + """ + return self._phone + + @phone.setter + def phone(self, phone): + """ + Sets the phone of this User. + + :param phone: The phone of this User. + :type phone: str + """ + + self._phone = phone + + @property + def user_status(self): + """ + Gets the user_status of this User. + User Status + + :return: The user_status of this User. + :rtype: int + """ + return self._user_status + + @user_status.setter + def user_status(self, user_status): + """ + Sets the user_status of this User. + User Status + + :param user_status: The user_status of this User. + :type user_status: int + """ + + self._user_status = user_status + diff --git a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml index 7b412611171..9e8598b591b 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml @@ -110,11 +110,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -607,10 +607,6 @@ paths: x-tags: - tag: "user" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -618,6 +614,10 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" definitions: Order: type: "object" diff --git a/samples/server/petstore/flaskConnexion-python2/util.py b/samples/server/petstore/flaskConnexion-python2/util.py new file mode 100644 index 00000000000..40c72d43ebd --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/util.py @@ -0,0 +1,149 @@ +from typing import GenericMeta +from datetime import datetime, date +from six import integer_types, iteritems + + +def _deserialize(data, klass): + """ + Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if klass in integer_types or klass in (float, str, bool): + return _deserialize_primitive(data, klass) + elif klass == object: + return _deserialize_object(data) + elif klass == date: + return deserialize_date(data) + elif klass == datetime: + return deserialize_datetime(data) + elif type(klass) == GenericMeta: + if klass.__extra__ == list: + return _deserialize_list(data, klass.__args__[0]) + if klass.__extra__ == dict: + return _deserialize_dict(data, klass.__args__[1]) + else: + return deserialize_model(data, klass) + + +def _deserialize_primitive(data, klass): + """ + Deserializes to primitive type. + + :param data: data to deserialize. + :param klass: class literal. + + :return: int, long, float, str, bool. + :rtype: int | long | float | str | bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + +def _deserialize_object(value): + """ + Return a original value. + + :return: object. + """ + return value + + +def deserialize_date(string): + """ + Deserializes string to date. + + :param string: str. + :type string: str + :return: date. + :rtype: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + + +def deserialize_datetime(string): + """ + Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :type string: str + :return: datetime. + :rtype: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + + +def deserialize_model(data, klass): + """ + Deserializes list or dict to model. + + :param data: dict, list. + :type data: dict | list + :param klass: class literal. + :return: model object. + """ + instance = klass() + + if not instance.swagger_types: + return data + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data \ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, _deserialize(value, attr_type)) + + return instance + + +def _deserialize_list(data, boxed_type): + """ + Deserializes a list and its elements. + + :param data: list to deserialize. + :type data: list + :param boxed_type: class literal. + + :return: deserialized list. + :rtype: list + """ + return [_deserialize(sub_data, boxed_type) + for sub_data in data] + + + +def _deserialize_dict(data, boxed_type): + """ + Deserializes a dict and its elements. + + :param data: dict to deserialize. + :type data: dict + :param boxed_type: class literal. + + :return: deserialized dict. + :rtype: dict + """ + return {k: _deserialize(v, boxed_type) + for k, v in iteritems(data)} diff --git a/samples/server/petstore/flaskConnexion/app.py b/samples/server/petstore/flaskConnexion/app.py index 0b3ce76dd2f..c5342f15859 100644 --- a/samples/server/petstore/flaskConnexion/app.py +++ b/samples/server/petstore/flaskConnexion/app.py @@ -1,8 +1,29 @@ #!/usr/bin/env python3 import connexion +from connexion.decorators import produces +from six import iteritems +from models.base_model_ import Model + + +class JSONEncoder(produces.JSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return produces.JSONEncoder.default(self, o) + if __name__ == '__main__': app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion/controllers/init.py b/samples/server/petstore/flaskConnexion/controllers/init.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py index b754758b21e..461f6163a63 100644 --- a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py @@ -1,24 +1,117 @@ +import connexion +from models.pet import Pet +from models.api_response import ApiResponse +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime -def add_pet(body) -> str: + +def add_pet(body): + """ + Add a new pet to the store + + :param body: Pet object that needs to be added to the store + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = Pet.from_dict(connexion.request.get_json()) return 'do some magic!' -def delete_pet(petId, apiKey = None) -> str: + +def delete_pet(petId, apiKey=None): + """ + Deletes a pet + + :param petId: Pet id to delete + :type petId: int + :param apiKey: + :type apiKey: str + + :rtype: None + """ return 'do some magic!' -def find_pets_by_status(status) -> str: + +def find_pets_by_status(status): + """ + Finds Pets by status + Multiple status values can be provided with comma separated strings + :param status: Status values that need to be considered for filter + :type status: List[str] + + :rtype: List[Pet] + """ return 'do some magic!' -def find_pets_by_tags(tags) -> str: + +def find_pets_by_tags(tags): + """ + Finds Pets by tags + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + :param tags: Tags to filter by + :type tags: List[str] + + :rtype: List[Pet] + """ return 'do some magic!' -def get_pet_by_id(petId) -> str: + +def get_pet_by_id(petId): + """ + Find pet by ID + Returns a single pet + :param petId: ID of pet to return + :type petId: int + + :rtype: Pet + """ return 'do some magic!' -def update_pet(body) -> str: + +def update_pet(body): + """ + Update an existing pet + + :param body: Pet object that needs to be added to the store + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = Pet.from_dict(connexion.request.get_json()) return 'do some magic!' -def update_pet_with_form(petId, name = None, status = None) -> str: + +def update_pet_with_form(petId, name=None, status=None): + """ + Updates a pet in the store with form data + + :param petId: ID of pet that needs to be updated + :type petId: int + :param name: Updated name of the pet + :type name: str + :param status: Updated status of the pet + :type status: str + + :rtype: None + """ return 'do some magic!' -def upload_file(petId, additionalMetadata = None, file = None) -> str: + +def upload_file(petId, additionalMetadata=None, file=None): + """ + uploads an image + + :param petId: ID of pet to update + :type petId: int + :param additionalMetadata: Additional data to pass to server + :type additionalMetadata: str + :param file: file to upload + :type file: werkzeug.datastructures.FileStorage + + :rtype: ApiResponse + """ return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/controllers/store_controller.py b/samples/server/petstore/flaskConnexion/controllers/store_controller.py index 5f5d893ff1e..5373cbf5f71 100644 --- a/samples/server/petstore/flaskConnexion/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/store_controller.py @@ -1,12 +1,54 @@ +import connexion +from models.order import Order +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime -def delete_order(orderId) -> str: + +def delete_order(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 + :type orderId: str + + :rtype: None + """ return 'do some magic!' -def get_inventory() -> str: + +def get_inventory(): + """ + Returns pet inventories by status + Returns a map of status codes to quantities + + :rtype: Dict[str, int] + """ return 'do some magic!' -def get_order_by_id(orderId) -> str: + +def get_order_by_id(orderId): + """ + 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 + :type orderId: int + + :rtype: Order + """ return 'do some magic!' -def place_order(body) -> str: + +def place_order(body): + """ + Place an order for a pet + + :param body: order placed for purchasing the pet + :type body: dict | bytes + + :rtype: Order + """ + if connexion.request.is_json: + body = Order.from_dict(connexion.request.get_json()) return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/controllers/user_controller.py b/samples/server/petstore/flaskConnexion/controllers/user_controller.py index a040086a508..0e406488a7f 100644 --- a/samples/server/petstore/flaskConnexion/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/user_controller.py @@ -1,24 +1,112 @@ +import connexion +from models.user import User +from datetime import date, datetime +from typing import List, Dict +from six import iteritems +from util import deserialize_date, deserialize_datetime -def create_user(body) -> str: + +def create_user(body): + """ + Create user + This can only be done by the logged in user. + :param body: Created user object + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = User.from_dict(connexion.request.get_json()) return 'do some magic!' -def create_users_with_array_input(body) -> str: + +def create_users_with_array_input(body): + """ + Creates list of users with given input array + + :param body: List of user object + :type body: list | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = [User.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!' -def create_users_with_list_input(body) -> str: + +def create_users_with_list_input(body): + """ + Creates list of users with given input array + + :param body: List of user object + :type body: list | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = [User.from_dict(d) for d in connexion.request.get_json()] return 'do some magic!' -def delete_user(username) -> str: + +def delete_user(username): + """ + Delete user + This can only be done by the logged in user. + :param username: The name that needs to be deleted + :type username: str + + :rtype: None + """ return 'do some magic!' -def get_user_by_name(username) -> str: + +def get_user_by_name(username): + """ + Get user by user name + + :param username: The name that needs to be fetched. Use user1 for testing. + :type username: str + + :rtype: User + """ return 'do some magic!' -def login_user(username, password) -> str: + +def login_user(username, password): + """ + Logs user into the system + + :param username: The user name for login + :type username: str + :param password: The password for login in clear text + :type password: str + + :rtype: str + """ return 'do some magic!' -def logout_user() -> str: + +def logout_user(): + """ + Logs out current logged in user session + + + :rtype: None + """ return 'do some magic!' -def update_user(username, body) -> str: + +def update_user(username, body): + """ + Updated user + This can only be done by the logged in user. + :param username: name that need to be deleted + :type username: str + :param body: Updated user object + :type body: dict | bytes + + :rtype: None + """ + if connexion.request.is_json: + body = User.from_dict(connexion.request.get_json()) return 'do some magic!' diff --git a/samples/server/petstore/flaskConnexion/init.py b/samples/server/petstore/flaskConnexion/init.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/samples/server/petstore/flaskConnexion/models/__init__.py b/samples/server/petstore/flaskConnexion/models/__init__.py new file mode 100644 index 00000000000..6571ad28e0f --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/__init__.py @@ -0,0 +1,10 @@ +# coding: utf-8 + +from __future__ import absolute_import +# import models into model package +from .api_response import ApiResponse +from .category import Category +from .order import Order +from .pet import Pet +from .tag import Tag +from .user import User diff --git a/samples/server/petstore/flaskConnexion/models/api_response.py b/samples/server/petstore/flaskConnexion/models/api_response.py new file mode 100644 index 00000000000..607a47e4dd4 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/api_response.py @@ -0,0 +1,116 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class ApiResponse(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, code: int=None, type: str=None, message: str=None): + """ + ApiResponse - a model defined in Swagger + + :param code: The code of this ApiResponse. + :type code: int + :param type: The type of this ApiResponse. + :type type: str + :param message: The message of this ApiResponse. + :type message: str + """ + self.swagger_types = { + 'code': int, + 'type': str, + 'message': str + } + + self.attribute_map = { + 'code': 'code', + 'type': 'type', + 'message': 'message' + } + + self._code = code + self._type = type + self._message = message + + @classmethod + def from_dict(cls, dikt) -> 'ApiResponse': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The ApiResponse of this ApiResponse. + :rtype: ApiResponse + """ + return deserialize_model(dikt, cls) + + @property + def code(self) -> int: + """ + Gets the code of this ApiResponse. + + :return: The code of this ApiResponse. + :rtype: int + """ + return self._code + + @code.setter + def code(self, code: int): + """ + Sets the code of this ApiResponse. + + :param code: The code of this ApiResponse. + :type code: int + """ + + self._code = code + + @property + def type(self) -> str: + """ + Gets the type of this ApiResponse. + + :return: The type of this ApiResponse. + :rtype: str + """ + return self._type + + @type.setter + def type(self, type: str): + """ + Sets the type of this ApiResponse. + + :param type: The type of this ApiResponse. + :type type: str + """ + + self._type = type + + @property + def message(self) -> str: + """ + Gets the message of this ApiResponse. + + :return: The message of this ApiResponse. + :rtype: str + """ + return self._message + + @message.setter + def message(self, message: str): + """ + Sets the message of this ApiResponse. + + :param message: The message of this ApiResponse. + :type message: str + """ + + self._message = message + diff --git a/samples/server/petstore/flaskConnexion/models/base_model_.py b/samples/server/petstore/flaskConnexion/models/base_model_.py new file mode 100644 index 00000000000..d10efa4f2c6 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/base_model_.py @@ -0,0 +1,75 @@ +from pprint import pformat +from typing import TypeVar, Type +from six import iteritems +from util import deserialize_model + +T = TypeVar('T') + + +class Model(object): + # swaggerTypes: The key is attribute name and the value is attribute type. + swagger_types = {} + + # attributeMap: The key is attribute name and the value is json key in definition. + attribute_map = {} + + @classmethod + def from_dict(cls: Type[T], dikt) -> T: + """ + Returns the dict as a model + """ + return deserialize_model(dikt, cls) + + def to_dict(self): + """ + Returns the model properties as a dict + + :rtype: dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + + :rtype: str + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion/models/category.py b/samples/server/petstore/flaskConnexion/models/category.py new file mode 100644 index 00000000000..e36ffb3bffa --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/category.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Category(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, name: str=None): + """ + Category - a model defined in Swagger + + :param id: The id of this Category. + :type id: int + :param name: The name of this Category. + :type name: str + """ + self.swagger_types = { + 'id': int, + 'name': str + } + + self.attribute_map = { + 'id': 'id', + 'name': 'name' + } + + self._id = id + self._name = name + + @classmethod + def from_dict(cls, dikt) -> 'Category': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Category of this Category. + :rtype: Category + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this Category. + + :return: The id of this Category. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this Category. + + :param id: The id of this Category. + :type id: int + """ + + self._id = id + + @property + def name(self) -> str: + """ + Gets the name of this Category. + + :return: The name of this Category. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """ + Sets the name of this Category. + + :param name: The name of this Category. + :type name: str + """ + + self._name = name + diff --git a/samples/server/petstore/flaskConnexion/models/order.py b/samples/server/petstore/flaskConnexion/models/order.py new file mode 100644 index 00000000000..1b4ad9f849d --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/order.py @@ -0,0 +1,202 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Order(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, pet_id: int=None, quantity: int=None, ship_date: datetime=None, status: str=None, complete: bool=False): + """ + Order - a model defined in Swagger + + :param id: The id of this Order. + :type id: int + :param pet_id: The pet_id of this Order. + :type pet_id: int + :param quantity: The quantity of this Order. + :type quantity: int + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + :param status: The status of this Order. + :type status: str + :param complete: The complete of this Order. + :type complete: bool + """ + self.swagger_types = { + 'id': int, + 'pet_id': int, + 'quantity': int, + 'ship_date': datetime, + 'status': str, + 'complete': bool + } + + self.attribute_map = { + 'id': 'id', + 'pet_id': 'petId', + 'quantity': 'quantity', + 'ship_date': 'shipDate', + 'status': 'status', + 'complete': 'complete' + } + + self._id = id + self._pet_id = pet_id + self._quantity = quantity + self._ship_date = ship_date + self._status = status + self._complete = complete + + @classmethod + def from_dict(cls, dikt) -> 'Order': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Order of this Order. + :rtype: Order + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this Order. + + :return: The id of this Order. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this Order. + + :param id: The id of this Order. + :type id: int + """ + + self._id = id + + @property + def pet_id(self) -> int: + """ + Gets the pet_id of this Order. + + :return: The pet_id of this Order. + :rtype: int + """ + return self._pet_id + + @pet_id.setter + def pet_id(self, pet_id: int): + """ + Sets the pet_id of this Order. + + :param pet_id: The pet_id of this Order. + :type pet_id: int + """ + + self._pet_id = pet_id + + @property + def quantity(self) -> int: + """ + Gets the quantity of this Order. + + :return: The quantity of this Order. + :rtype: int + """ + return self._quantity + + @quantity.setter + def quantity(self, quantity: int): + """ + Sets the quantity of this Order. + + :param quantity: The quantity of this Order. + :type quantity: int + """ + + self._quantity = quantity + + @property + def ship_date(self) -> datetime: + """ + Gets the ship_date of this Order. + + :return: The ship_date of this Order. + :rtype: datetime + """ + return self._ship_date + + @ship_date.setter + def ship_date(self, ship_date: datetime): + """ + Sets the ship_date of this Order. + + :param ship_date: The ship_date of this Order. + :type ship_date: datetime + """ + + self._ship_date = ship_date + + @property + def status(self) -> str: + """ + Gets the status of this Order. + Order Status + + :return: The status of this Order. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status: str): + """ + Sets the status of this Order. + Order Status + + :param status: The status of this Order. + :type status: str + """ + allowed_values = ["placed", "approved", "delivered"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) + ) + + self._status = status + + @property + def complete(self) -> bool: + """ + Gets the complete of this Order. + + :return: The complete of this Order. + :rtype: bool + """ + return self._complete + + @complete.setter + def complete(self, complete: bool): + """ + Sets the complete of this Order. + + :param complete: The complete of this Order. + :type complete: bool + """ + + self._complete = complete + diff --git a/samples/server/petstore/flaskConnexion/models/pet.py b/samples/server/petstore/flaskConnexion/models/pet.py new file mode 100644 index 00000000000..11ad67f7649 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/pet.py @@ -0,0 +1,208 @@ +# coding: utf-8 + +from __future__ import absolute_import +from models.category import Category +from models.tag import Tag +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Pet(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, category: Category=None, name: str=None, photo_urls: List[str]=None, tags: List[Tag]=None, status: str=None): + """ + Pet - a model defined in Swagger + + :param id: The id of this Pet. + :type id: int + :param category: The category of this Pet. + :type category: Category + :param name: The name of this Pet. + :type name: str + :param photo_urls: The photo_urls of this Pet. + :type photo_urls: List[str] + :param tags: The tags of this Pet. + :type tags: List[Tag] + :param status: The status of this Pet. + :type status: str + """ + self.swagger_types = { + 'id': int, + 'category': Category, + 'name': str, + 'photo_urls': List[str], + 'tags': List[Tag], + 'status': str + } + + self.attribute_map = { + 'id': 'id', + 'category': 'category', + 'name': 'name', + 'photo_urls': 'photoUrls', + 'tags': 'tags', + 'status': 'status' + } + + self._id = id + self._category = category + self._name = name + self._photo_urls = photo_urls + self._tags = tags + self._status = status + + @classmethod + def from_dict(cls, dikt) -> 'Pet': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Pet of this Pet. + :rtype: Pet + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this Pet. + + :return: The id of this Pet. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this Pet. + + :param id: The id of this Pet. + :type id: int + """ + + self._id = id + + @property + def category(self) -> Category: + """ + Gets the category of this Pet. + + :return: The category of this Pet. + :rtype: Category + """ + return self._category + + @category.setter + def category(self, category: Category): + """ + Sets the category of this Pet. + + :param category: The category of this Pet. + :type category: Category + """ + + self._category = category + + @property + def name(self) -> str: + """ + Gets the name of this Pet. + + :return: The name of this Pet. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """ + Sets the name of this Pet. + + :param name: The name of this Pet. + :type name: str + """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") + + self._name = name + + @property + def photo_urls(self) -> List[str]: + """ + Gets the photo_urls of this Pet. + + :return: The photo_urls of this Pet. + :rtype: List[str] + """ + return self._photo_urls + + @photo_urls.setter + def photo_urls(self, photo_urls: List[str]): + """ + Sets the photo_urls of this Pet. + + :param photo_urls: The photo_urls of this Pet. + :type photo_urls: List[str] + """ + if photo_urls is None: + raise ValueError("Invalid value for `photo_urls`, must not be `None`") + + self._photo_urls = photo_urls + + @property + def tags(self) -> List[Tag]: + """ + Gets the tags of this Pet. + + :return: The tags of this Pet. + :rtype: List[Tag] + """ + return self._tags + + @tags.setter + def tags(self, tags: List[Tag]): + """ + Sets the tags of this Pet. + + :param tags: The tags of this Pet. + :type tags: List[Tag] + """ + + self._tags = tags + + @property + def status(self) -> str: + """ + Gets the status of this Pet. + pet status in the store + + :return: The status of this Pet. + :rtype: str + """ + return self._status + + @status.setter + def status(self, status: str): + """ + Sets the status of this Pet. + pet status in the store + + :param status: The status of this Pet. + :type status: str + """ + allowed_values = ["available", "pending", "sold"] + if status not in allowed_values: + raise ValueError( + "Invalid value for `status` ({0}), must be one of {1}" + .format(status, allowed_values) + ) + + self._status = status + diff --git a/samples/server/petstore/flaskConnexion/models/tag.py b/samples/server/petstore/flaskConnexion/models/tag.py new file mode 100644 index 00000000000..41f1b024fe8 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/tag.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class Tag(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, name: str=None): + """ + Tag - a model defined in Swagger + + :param id: The id of this Tag. + :type id: int + :param name: The name of this Tag. + :type name: str + """ + self.swagger_types = { + 'id': int, + 'name': str + } + + self.attribute_map = { + 'id': 'id', + 'name': 'name' + } + + self._id = id + self._name = name + + @classmethod + def from_dict(cls, dikt) -> 'Tag': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The Tag of this Tag. + :rtype: Tag + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this Tag. + + :return: The id of this Tag. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this Tag. + + :param id: The id of this Tag. + :type id: int + """ + + self._id = id + + @property + def name(self) -> str: + """ + Gets the name of this Tag. + + :return: The name of this Tag. + :rtype: str + """ + return self._name + + @name.setter + def name(self, name: str): + """ + Sets the name of this Tag. + + :param name: The name of this Tag. + :type name: str + """ + + self._name = name + diff --git a/samples/server/petstore/flaskConnexion/models/user.py b/samples/server/petstore/flaskConnexion/models/user.py new file mode 100644 index 00000000000..77fdaa7a252 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/models/user.py @@ -0,0 +1,248 @@ +# coding: utf-8 + +from __future__ import absolute_import +from .base_model_ import Model +from datetime import date, datetime +from typing import List, Dict +from util import deserialize_model + + +class User(Model): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, id: int=None, username: str=None, first_name: str=None, last_name: str=None, email: str=None, password: str=None, phone: str=None, user_status: int=None): + """ + User - a model defined in Swagger + + :param id: The id of this User. + :type id: int + :param username: The username of this User. + :type username: str + :param first_name: The first_name of this User. + :type first_name: str + :param last_name: The last_name of this User. + :type last_name: str + :param email: The email of this User. + :type email: str + :param password: The password of this User. + :type password: str + :param phone: The phone of this User. + :type phone: str + :param user_status: The user_status of this User. + :type user_status: int + """ + self.swagger_types = { + 'id': int, + 'username': str, + 'first_name': str, + 'last_name': str, + 'email': str, + 'password': str, + 'phone': str, + 'user_status': int + } + + self.attribute_map = { + 'id': 'id', + 'username': 'username', + 'first_name': 'firstName', + 'last_name': 'lastName', + 'email': 'email', + 'password': 'password', + 'phone': 'phone', + 'user_status': 'userStatus' + } + + self._id = id + self._username = username + self._first_name = first_name + self._last_name = last_name + self._email = email + self._password = password + self._phone = phone + self._user_status = user_status + + @classmethod + def from_dict(cls, dikt) -> 'User': + """ + Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The User of this User. + :rtype: User + """ + return deserialize_model(dikt, cls) + + @property + def id(self) -> int: + """ + Gets the id of this User. + + :return: The id of this User. + :rtype: int + """ + return self._id + + @id.setter + def id(self, id: int): + """ + Sets the id of this User. + + :param id: The id of this User. + :type id: int + """ + + self._id = id + + @property + def username(self) -> str: + """ + Gets the username of this User. + + :return: The username of this User. + :rtype: str + """ + return self._username + + @username.setter + def username(self, username: str): + """ + Sets the username of this User. + + :param username: The username of this User. + :type username: str + """ + + self._username = username + + @property + def first_name(self) -> str: + """ + Gets the first_name of this User. + + :return: The first_name of this User. + :rtype: str + """ + return self._first_name + + @first_name.setter + def first_name(self, first_name: str): + """ + Sets the first_name of this User. + + :param first_name: The first_name of this User. + :type first_name: str + """ + + self._first_name = first_name + + @property + def last_name(self) -> str: + """ + Gets the last_name of this User. + + :return: The last_name of this User. + :rtype: str + """ + return self._last_name + + @last_name.setter + def last_name(self, last_name: str): + """ + Sets the last_name of this User. + + :param last_name: The last_name of this User. + :type last_name: str + """ + + self._last_name = last_name + + @property + def email(self) -> str: + """ + Gets the email of this User. + + :return: The email of this User. + :rtype: str + """ + return self._email + + @email.setter + def email(self, email: str): + """ + Sets the email of this User. + + :param email: The email of this User. + :type email: str + """ + + self._email = email + + @property + def password(self) -> str: + """ + Gets the password of this User. + + :return: The password of this User. + :rtype: str + """ + return self._password + + @password.setter + def password(self, password: str): + """ + Sets the password of this User. + + :param password: The password of this User. + :type password: str + """ + + self._password = password + + @property + def phone(self) -> str: + """ + Gets the phone of this User. + + :return: The phone of this User. + :rtype: str + """ + return self._phone + + @phone.setter + def phone(self, phone: str): + """ + Sets the phone of this User. + + :param phone: The phone of this User. + :type phone: str + """ + + self._phone = phone + + @property + def user_status(self) -> int: + """ + Gets the user_status of this User. + User Status + + :return: The user_status of this User. + :rtype: int + """ + return self._user_status + + @user_status.setter + def user_status(self, user_status: int): + """ + Sets the user_status of this User. + User Status + + :param user_status: The user_status of this User. + :type user_status: int + """ + + self._user_status = user_status + diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml index 7b412611171..9e8598b591b 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -110,11 +110,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -607,10 +607,6 @@ paths: x-tags: - tag: "user" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -618,6 +614,10 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" definitions: Order: type: "object" diff --git a/samples/server/petstore/flaskConnexion/util.py b/samples/server/petstore/flaskConnexion/util.py new file mode 100644 index 00000000000..40c72d43ebd --- /dev/null +++ b/samples/server/petstore/flaskConnexion/util.py @@ -0,0 +1,149 @@ +from typing import GenericMeta +from datetime import datetime, date +from six import integer_types, iteritems + + +def _deserialize(data, klass): + """ + Deserializes dict, list, str into an object. + + :param data: dict, list or str. + :param klass: class literal, or string of class name. + + :return: object. + """ + if data is None: + return None + + if klass in integer_types or klass in (float, str, bool): + return _deserialize_primitive(data, klass) + elif klass == object: + return _deserialize_object(data) + elif klass == date: + return deserialize_date(data) + elif klass == datetime: + return deserialize_datetime(data) + elif type(klass) == GenericMeta: + if klass.__extra__ == list: + return _deserialize_list(data, klass.__args__[0]) + if klass.__extra__ == dict: + return _deserialize_dict(data, klass.__args__[1]) + else: + return deserialize_model(data, klass) + + +def _deserialize_primitive(data, klass): + """ + Deserializes to primitive type. + + :param data: data to deserialize. + :param klass: class literal. + + :return: int, long, float, str, bool. + :rtype: int | long | float | str | bool + """ + try: + value = klass(data) + except UnicodeEncodeError: + value = unicode(data) + except TypeError: + value = data + return value + + +def _deserialize_object(value): + """ + Return a original value. + + :return: object. + """ + return value + + +def deserialize_date(string): + """ + Deserializes string to date. + + :param string: str. + :type string: str + :return: date. + :rtype: date + """ + try: + from dateutil.parser import parse + return parse(string).date() + except ImportError: + return string + + +def deserialize_datetime(string): + """ + Deserializes string to datetime. + + The string should be in iso8601 datetime format. + + :param string: str. + :type string: str + :return: datetime. + :rtype: datetime + """ + try: + from dateutil.parser import parse + return parse(string) + except ImportError: + return string + + +def deserialize_model(data, klass): + """ + Deserializes list or dict to model. + + :param data: dict, list. + :type data: dict | list + :param klass: class literal. + :return: model object. + """ + instance = klass() + + if not instance.swagger_types: + return data + + for attr, attr_type in iteritems(instance.swagger_types): + if data is not None \ + and instance.attribute_map[attr] in data \ + and isinstance(data, (list, dict)): + value = data[instance.attribute_map[attr]] + setattr(instance, attr, _deserialize(value, attr_type)) + + return instance + + +def _deserialize_list(data, boxed_type): + """ + Deserializes a list and its elements. + + :param data: list to deserialize. + :type data: list + :param boxed_type: class literal. + + :return: deserialized list. + :rtype: list + """ + return [_deserialize(sub_data, boxed_type) + for sub_data in data] + + + +def _deserialize_dict(data, boxed_type): + """ + Deserializes a dict and its elements. + + :param data: dict to deserialize. + :type data: dict + :param boxed_type: class literal. + + :return: deserialized dict. + :rtype: dict + """ + return {k: _deserialize(v, boxed_type) + for k, v in iteritems(data)} From 1e6cab8a030f8a76405f886aa2849889b40ff030 Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 15 Nov 2016 17:34:56 +0100 Subject: [PATCH 068/269] [Flask] Use x-swagger-router-controller in swagger.yaml for operation routing Fix #4106 --- .../languages/FlaskConnexionCodegen.java | 66 ++++------- .../swagger/swagger.yaml | 110 +++++++----------- .../flaskConnexion/swagger/swagger.yaml | 110 +++++++----------- 3 files changed, 112 insertions(+), 174 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 2ac51c7e9e1..ad4d8f625e7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -227,52 +227,30 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf @Override public void preprocessSwagger(Swagger swagger) { - if (swagger != null && swagger.getPaths() != null) { - for(String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for(Map.Entry entry : path.getOperationMap().entrySet()) { - // Normalize `operationId` and add package/class path in front, e.g. - // controllers.default_controller.add_pet - String httpMethod = entry.getKey().name().toLowerCase(); - Operation operation = entry.getValue(); - String operationId = getOrGenerateOperationId(operation, pathname, httpMethod); - String controllerName; - - if (operation.getTags() != null) { - List> tags = new ArrayList>(); - for(String tag : operation.getTags()) { - Map value = new HashMap(); - value.put("tag", tag); - value.put("hasMore", "true"); - tags.add(value); - } - - if (tags.size() > 0) { - tags.get(tags.size() - 1).remove("hasMore"); - } - - // use only the first tag - if (operation.getTags().size() > 0) { - String tag = operation.getTags().get(0); - operation.setTags(Arrays.asList(tag)); - controllerName = tag + "_controller"; - } else { - controllerName = "default_controller"; - } - - operation.setVendorExtension("x-tags", tags); + // need vendor extensions for x-swagger-router-controller + Map paths = swagger.getPaths(); + if(paths != null) { + for(String pathname : paths.keySet()) { + Path path = paths.get(pathname); + Map operationMap = path.getOperationMap(); + if(operationMap != null) { + for(HttpMethod method : operationMap.keySet()) { + Operation operation = operationMap.get(method); + String tag = "default"; + if(operation.getTags() != null && operation.getTags().size() > 0) { + tag = operation.getTags().get(0); } - else { - // no tag found, use "default_controller" as the default - String tag = "default"; - operation.setTags(Arrays.asList(tag)); - controllerName = tag + "_controller"; + String operationId = operation.getOperationId(); + if(operationId == null) { + operationId = getOrGenerateOperationId(operation, pathname, method.toString()); + } + operation.setOperationId(toOperationId(operationId)); + if(operation.getVendorExtensions().get("x-swagger-router-controller") == null) { + operation.getVendorExtensions().put( + "x-swagger-router-controller", + controllerPackage + "." + toApiFilename(tag) + ); } - - operationId = underscore(sanitizeName(operationId)); - operationId = controllerPackage + "." + controllerName + "." + operationId; - operation.setOperationId(operationId); } } } diff --git a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml index 7b412611171..3d22ab2d847 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml @@ -37,7 +37,7 @@ paths: - "pet" summary: "Add a new pet to the store" description: "" - operationId: "controllers.pet_controller.add_pet" + operationId: "add_pet" consumes: - "application/json" - "application/xml" @@ -58,14 +58,13 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" put: tags: - "pet" summary: "Update an existing pet" description: "" - operationId: "controllers.pet_controller.update_pet" + operationId: "update_pet" consumes: - "application/json" - "application/xml" @@ -90,15 +89,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/findByStatus: get: tags: - "pet" summary: "Finds Pets by status" description: "Multiple status values can be provided with comma separated strings" - operationId: "controllers.pet_controller.find_pets_by_status" + operationId: "find_pets_by_status" produces: - "application/xml" - "application/json" @@ -110,11 +108,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -129,8 +127,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/findByTags: get: tags: @@ -138,7 +135,7 @@ paths: summary: "Finds Pets by tags" description: "Multiple tags can be provided with comma separated strings. Use\ \ tag1, tag2, tag3 for testing." - operationId: "controllers.pet_controller.find_pets_by_tags" + operationId: "find_pets_by_tags" produces: - "application/xml" - "application/json" @@ -164,15 +161,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/{petId}: get: tags: - "pet" summary: "Find pet by ID" description: "Returns a single pet" - operationId: "controllers.pet_controller.get_pet_by_id" + operationId: "get_pet_by_id" produces: - "application/xml" - "application/json" @@ -194,14 +190,13 @@ paths: description: "Pet not found" security: - api_key: [] - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" post: tags: - "pet" summary: "Updates a pet in the store with form data" description: "" - operationId: "controllers.pet_controller.update_pet_with_form" + operationId: "update_pet_with_form" consumes: - "application/x-www-form-urlencoded" produces: @@ -231,14 +226,13 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" delete: tags: - "pet" summary: "Deletes a pet" description: "" - operationId: "controllers.pet_controller.delete_pet" + operationId: "delete_pet" produces: - "application/xml" - "application/json" @@ -260,15 +254,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/{petId}/uploadImage: post: tags: - "pet" summary: "uploads an image" description: "" - operationId: "controllers.pet_controller.upload_file" + operationId: "upload_file" consumes: - "multipart/form-data" produces: @@ -299,15 +292,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /store/inventory: get: tags: - "store" summary: "Returns pet inventories by status" description: "Returns a map of status codes to quantities" - operationId: "controllers.store_controller.get_inventory" + operationId: "get_inventory" produces: - "application/json" parameters: [] @@ -321,15 +313,14 @@ paths: format: "int32" security: - api_key: [] - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /store/order: post: tags: - "store" summary: "Place an order for a pet" description: "" - operationId: "controllers.store_controller.place_order" + operationId: "place_order" produces: - "application/xml" - "application/json" @@ -347,8 +338,7 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /store/order/{orderId}: get: tags: @@ -356,7 +346,7 @@ paths: summary: "Find purchase order by ID" description: "For valid response try integer IDs with value <= 5 or > 10. Other\ \ values will generated exceptions" - operationId: "controllers.store_controller.get_order_by_id" + operationId: "get_order_by_id" produces: - "application/xml" - "application/json" @@ -378,15 +368,14 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" delete: tags: - "store" summary: "Delete purchase order by ID" description: "For valid response try integer IDs with value < 1000. Anything\ \ above 1000 or nonintegers will generate API errors" - operationId: "controllers.store_controller.delete_order" + operationId: "delete_order" produces: - "application/xml" - "application/json" @@ -402,15 +391,14 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /user: post: tags: - "user" summary: "Create user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.create_user" + operationId: "create_user" produces: - "application/xml" - "application/json" @@ -424,15 +412,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/createWithArray: post: tags: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.user_controller.create_users_with_array_input" + operationId: "create_users_with_array_input" produces: - "application/xml" - "application/json" @@ -448,15 +435,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/createWithList: post: tags: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.user_controller.create_users_with_list_input" + operationId: "create_users_with_list_input" produces: - "application/xml" - "application/json" @@ -472,15 +458,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/login: get: tags: - "user" summary: "Logs user into the system" description: "" - operationId: "controllers.user_controller.login_user" + operationId: "login_user" produces: - "application/xml" - "application/json" @@ -511,15 +496,14 @@ paths: description: "date in UTC when toekn expires" 400: description: "Invalid username/password supplied" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/logout: get: tags: - "user" summary: "Logs out current logged in user session" description: "" - operationId: "controllers.user_controller.logout_user" + operationId: "logout_user" produces: - "application/xml" - "application/json" @@ -527,15 +511,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/{username}: get: tags: - "user" summary: "Get user by user name" description: "" - operationId: "controllers.user_controller.get_user_by_name" + operationId: "get_user_by_name" produces: - "application/xml" - "application/json" @@ -554,14 +537,13 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" put: tags: - "user" summary: "Updated user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.update_user" + operationId: "update_user" produces: - "application/xml" - "application/json" @@ -582,14 +564,13 @@ paths: description: "Invalid user supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" delete: tags: - "user" summary: "Delete user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.delete_user" + operationId: "delete_user" produces: - "application/xml" - "application/json" @@ -604,13 +585,8 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -618,6 +594,10 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" definitions: Order: type: "object" diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml index 7b412611171..3d22ab2d847 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger/swagger.yaml @@ -37,7 +37,7 @@ paths: - "pet" summary: "Add a new pet to the store" description: "" - operationId: "controllers.pet_controller.add_pet" + operationId: "add_pet" consumes: - "application/json" - "application/xml" @@ -58,14 +58,13 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" put: tags: - "pet" summary: "Update an existing pet" description: "" - operationId: "controllers.pet_controller.update_pet" + operationId: "update_pet" consumes: - "application/json" - "application/xml" @@ -90,15 +89,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/findByStatus: get: tags: - "pet" summary: "Finds Pets by status" description: "Multiple status values can be provided with comma separated strings" - operationId: "controllers.pet_controller.find_pets_by_status" + operationId: "find_pets_by_status" produces: - "application/xml" - "application/json" @@ -110,11 +108,11 @@ paths: type: "array" items: type: "string" - default: "available" enum: - "available" - "pending" - "sold" + default: "available" collectionFormat: "csv" responses: 200: @@ -129,8 +127,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/findByTags: get: tags: @@ -138,7 +135,7 @@ paths: summary: "Finds Pets by tags" description: "Multiple tags can be provided with comma separated strings. Use\ \ tag1, tag2, tag3 for testing." - operationId: "controllers.pet_controller.find_pets_by_tags" + operationId: "find_pets_by_tags" produces: - "application/xml" - "application/json" @@ -164,15 +161,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/{petId}: get: tags: - "pet" summary: "Find pet by ID" description: "Returns a single pet" - operationId: "controllers.pet_controller.get_pet_by_id" + operationId: "get_pet_by_id" produces: - "application/xml" - "application/json" @@ -194,14 +190,13 @@ paths: description: "Pet not found" security: - api_key: [] - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" post: tags: - "pet" summary: "Updates a pet in the store with form data" description: "" - operationId: "controllers.pet_controller.update_pet_with_form" + operationId: "update_pet_with_form" consumes: - "application/x-www-form-urlencoded" produces: @@ -231,14 +226,13 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" delete: tags: - "pet" summary: "Deletes a pet" description: "" - operationId: "controllers.pet_controller.delete_pet" + operationId: "delete_pet" produces: - "application/xml" - "application/json" @@ -260,15 +254,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /pet/{petId}/uploadImage: post: tags: - "pet" summary: "uploads an image" description: "" - operationId: "controllers.pet_controller.upload_file" + operationId: "upload_file" consumes: - "multipart/form-data" produces: @@ -299,15 +292,14 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-tags: - - tag: "pet" + x-swagger-router-controller: "controllers.pet_controller" /store/inventory: get: tags: - "store" summary: "Returns pet inventories by status" description: "Returns a map of status codes to quantities" - operationId: "controllers.store_controller.get_inventory" + operationId: "get_inventory" produces: - "application/json" parameters: [] @@ -321,15 +313,14 @@ paths: format: "int32" security: - api_key: [] - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /store/order: post: tags: - "store" summary: "Place an order for a pet" description: "" - operationId: "controllers.store_controller.place_order" + operationId: "place_order" produces: - "application/xml" - "application/json" @@ -347,8 +338,7 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /store/order/{orderId}: get: tags: @@ -356,7 +346,7 @@ paths: summary: "Find purchase order by ID" description: "For valid response try integer IDs with value <= 5 or > 10. Other\ \ values will generated exceptions" - operationId: "controllers.store_controller.get_order_by_id" + operationId: "get_order_by_id" produces: - "application/xml" - "application/json" @@ -378,15 +368,14 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" delete: tags: - "store" summary: "Delete purchase order by ID" description: "For valid response try integer IDs with value < 1000. Anything\ \ above 1000 or nonintegers will generate API errors" - operationId: "controllers.store_controller.delete_order" + operationId: "delete_order" produces: - "application/xml" - "application/json" @@ -402,15 +391,14 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-tags: - - tag: "store" + x-swagger-router-controller: "controllers.store_controller" /user: post: tags: - "user" summary: "Create user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.create_user" + operationId: "create_user" produces: - "application/xml" - "application/json" @@ -424,15 +412,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/createWithArray: post: tags: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.user_controller.create_users_with_array_input" + operationId: "create_users_with_array_input" produces: - "application/xml" - "application/json" @@ -448,15 +435,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/createWithList: post: tags: - "user" summary: "Creates list of users with given input array" description: "" - operationId: "controllers.user_controller.create_users_with_list_input" + operationId: "create_users_with_list_input" produces: - "application/xml" - "application/json" @@ -472,15 +458,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/login: get: tags: - "user" summary: "Logs user into the system" description: "" - operationId: "controllers.user_controller.login_user" + operationId: "login_user" produces: - "application/xml" - "application/json" @@ -511,15 +496,14 @@ paths: description: "date in UTC when toekn expires" 400: description: "Invalid username/password supplied" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/logout: get: tags: - "user" summary: "Logs out current logged in user session" description: "" - operationId: "controllers.user_controller.logout_user" + operationId: "logout_user" produces: - "application/xml" - "application/json" @@ -527,15 +511,14 @@ paths: responses: default: description: "successful operation" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" /user/{username}: get: tags: - "user" summary: "Get user by user name" description: "" - operationId: "controllers.user_controller.get_user_by_name" + operationId: "get_user_by_name" produces: - "application/xml" - "application/json" @@ -554,14 +537,13 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" put: tags: - "user" summary: "Updated user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.update_user" + operationId: "update_user" produces: - "application/xml" - "application/json" @@ -582,14 +564,13 @@ paths: description: "Invalid user supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" delete: tags: - "user" summary: "Delete user" description: "This can only be done by the logged in user." - operationId: "controllers.user_controller.delete_user" + operationId: "delete_user" produces: - "application/xml" - "application/json" @@ -604,13 +585,8 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-tags: - - tag: "user" + x-swagger-router-controller: "controllers.user_controller" securityDefinitions: - api_key: - type: "apiKey" - name: "api_key" - in: "header" petstore_auth: type: "oauth2" authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" @@ -618,6 +594,10 @@ securityDefinitions: scopes: write:pets: "modify pets in your account" read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" definitions: Order: type: "object" From 2dafdffce5fe02d5b3f0e67401f9bbaba31972e8 Mon Sep 17 00:00:00 2001 From: Herman Schistad Date: Fri, 18 Nov 2016 05:38:32 +0000 Subject: [PATCH 069/269] Allow multiple requests in parallel in Python client (#4187) * Allow multiple requests in parallel in Python client If you tried to do two parallel calls to the same API object in the Python client you would get an error from urllib3 connection pool: Connection pool is full, discarding connection: *** Because the default maxsize=1: https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L162 By defaulting to a higher maxsize we mitigate for the common use case where a user is running a couple of requests in parallel. Ideally, in the future, this should be a configuration paramater together with the pool size. * Add sample code after changing maxsize --- .../swagger-codegen/src/main/resources/python/rest.mustache | 4 +++- samples/client/petstore/python/petstore_api/rest.py | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 8ddd17c473c..910d3001edf 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -49,10 +49,11 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): - def __init__(self, pools_size=4): + def __init__(self, pools_size=4, maxsize=4): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # maxsize is the number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -78,6 +79,7 @@ class RESTClientObject(object): # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, + maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=cert_file, diff --git a/samples/client/petstore/python/petstore_api/rest.py b/samples/client/petstore/python/petstore_api/rest.py index a85e8c5bc74..5fda97044b3 100644 --- a/samples/client/petstore/python/petstore_api/rest.py +++ b/samples/client/petstore/python/petstore_api/rest.py @@ -58,10 +58,11 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): - def __init__(self, pools_size=4): + def __init__(self, pools_size=4, maxsize=4): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # maxsize is the number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -87,6 +88,7 @@ class RESTClientObject(object): # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, + maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=cert_file, From 61f6c943514d0c906ea215c043aae549b66b3524 Mon Sep 17 00:00:00 2001 From: Sanjeewa Malalgoda Date: Fri, 18 Nov 2016 11:13:11 +0530 Subject: [PATCH 070/269] update readme description (#4207) --- .../src/main/resources/MSF4J/README.mustache | 34 +++++++++++-------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/README.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/README.mustache index b8a8abc32ad..9c4267f9302 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/README.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/README.mustache @@ -1,23 +1,29 @@ -# Swagger Jersey generated server +# Swagger MSF4J generated server -## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the -[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled JAX-RS server. -This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. - -To run the server, please execute the following: +WSO2 Microservices Framework for Java (MSF4J) is a lightweight high performance framework for developing & running microservices. WSO2 MSF4J is one of the highest performing lightweight Java microservices frameworks. Now swagger code generator will generate micro service skeleton from swagger definition. So you can use this project to convert your swagger definitions to micro service quickly. With this approach you can develop complete micro service within seconds from your swagger definition. +MSF4J generator uses java-msf4j as the default library. +Before you build/run service replace .deploy(new PetApi()) with your actual service class name in Application.java file like .deploy(new ApisAPI()) then it will start that service. If you have multiple service classes add them in , separated manner. ``` -mvn clean package jetty:run + new MicroservicesRunner() + .deploy(new PetsApi()) + .start(); ``` -You can then view the swagger listing here: - +To Use-it : in the generated folder try ``` -http://localhost:{{serverPort}}{{contextPath}}/swagger.json +mvn package ``` -Note that if you have configured the `host` to be something other than localhost, the calls through -swagger-ui will be directed to that host and not localhost! \ No newline at end of file +for build jar, then start your server: +``` +java -jar target/micro-service-server-1.0.0.jar +``` + +Java Microservice listening on default port 8080. +Run the following command or simply go to http://127.0.0.1:8080/pet/12 from your browser: + +``` + curl http://127.0.0.1:8080/pet/12 +``` From b7e9603e63ad2220f0234c85ab749110f3b03858 Mon Sep 17 00:00:00 2001 From: Nick Maynard Date: Fri, 18 Nov 2016 06:00:53 +0000 Subject: [PATCH 071/269] jaxrs-cxf-cdi :: Add a basic JAX-RS Application and CDI fixes (#4196) * Add a basic JAX-RS Application and CDI fixes * jaxrs-cxf-cdi :: Fix samples generation template dir * jaxrs-cxf-cdi :: Regenerate samples * jaxrs-cxf-cdi :: Clean up some checkstyle warnings --- bin/jaxrs-cxf-cdi-petstore-server.sh | 2 +- .../JavaJAXRSCXFCDIServerCodegen.java | 31 ++- .../cxf-cdi/RestApplication.mustache | 9 + .../JavaJaxRS/cxf-cdi/beans.mustache | 13 ++ .../src/gen/java/io/swagger/api/PetApi.java | 142 ++++++++++--- .../java/io/swagger/api/PetApiService.java | 2 +- .../src/gen/java/io/swagger/api/StoreApi.java | 72 +++++-- .../java/io/swagger/api/StoreApiService.java | 2 +- .../src/gen/java/io/swagger/api/UserApi.java | 103 +++++++--- .../java/io/swagger/api/UserApiService.java | 2 +- .../gen/java/io/swagger/model/Category.java | 79 ++++--- .../io/swagger/model/ModelApiResponse.java | 98 +++++---- .../src/gen/java/io/swagger/model/Order.java | 190 +++++++++-------- .../src/gen/java/io/swagger/model/Pet.java | 190 +++++++++-------- .../src/gen/java/io/swagger/model/Tag.java | 79 ++++--- .../src/gen/java/io/swagger/model/User.java | 192 +++++++++++------- .../java/io/swagger/api/RestApplication.java | 9 + .../swagger/api/impl/PetApiServiceImpl.java | 113 +++++------ .../swagger/api/impl/StoreApiServiceImpl.java | 68 +++---- .../swagger/api/impl/UserApiServiceImpl.java | 112 +++++----- .../src/main/webapp/WEB-INF/beans.xml | 13 ++ .../petstore/jaxrs-cxf-cdi/swagger.json | 10 +- 22 files changed, 954 insertions(+), 577 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/RestApplication.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beans.mustache create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java create mode 100644 samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml diff --git a/bin/jaxrs-cxf-cdi-petstore-server.sh b/bin/jaxrs-cxf-cdi-petstore-server.sh index ca9874a3d3f..a7d5d4ed375 100755 --- a/bin/jaxrs-cxf-cdi-petstore-server.sh +++ b/bin/jaxrs-cxf-cdi-petstore-server.sh @@ -26,6 +26,6 @@ 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 -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-cdi -o samples/server/petstore/jaxrs-cxf-cdi -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf-cdi -o samples/server/petstore/jaxrs-cxf-cdi -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java index cdf83061d2b..be214dae514 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -1,12 +1,22 @@ package io.swagger.codegen.languages; -import io.swagger.codegen.*; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.SupportingFile; import java.io.File; +/** + * Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an + * Apache CXF runtime and a Java EE runtime with CDI enabled. + * Similar to the original JAXRS generator, this creates API and Service classes + * in /src/gen/java and a sample ServiceImpl in /src/main/java. The API uses CDI + * to get an instance of ServiceImpl that implements the Service interface. + */ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { + /** + * Default constructor + */ public JavaJAXRSCXFCDIServerCodegen() { outputFolder = "generated-code/JavaJaxRS-CXF-CDI"; artifactId = "swagger-jaxrs-cxf-cdi-server"; @@ -20,7 +30,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { typeMapping.put("DateTime", "java.util.Date"); // Updated template directory - embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + + File.separator + "cxf-cdi"; } @Override @@ -31,8 +42,21 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { @Override public void processOpts() { super.processOpts(); + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + + // writeOptional means these files are only written if they don't already exist + + // POM writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); + + // RestApplication into src/main/java + writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", + (implFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); + + // Make CDI work in containers with implicit archive scanning disabled + writeOptional(outputFolder, new SupportingFile("beans.mustache", + "src/main/webapp/WEB-INF", "beans.xml")); } @Override @@ -45,7 +69,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { @Override public String getHelp() { - return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an Apache CXF runtime and a Java EE runtime with CDI enabled."; + return "Generates a Java JAXRS Server according to JAXRS 2.0 specification, assuming an " + + "Apache CXF runtime and a Java EE runtime with CDI enabled."; } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/RestApplication.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/RestApplication.mustache new file mode 100644 index 00000000000..d3d8b238d72 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/RestApplication.mustache @@ -0,0 +1,9 @@ +package {{invokerPackage}}; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class RestApplication extends Application { + // Add implementation-specific details here +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beans.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beans.mustache new file mode 100644 index 00000000000..cb6d500d43f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beans.mustache @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java index 9323636fbda..df620e58666 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java @@ -3,78 +3,164 @@ package io.swagger.api; import java.io.File; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; +import io.swagger.api.PetApiService; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; import javax.ws.rs.*; +import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; -import org.apache.cxf.jaxrs.ext.multipart.*; +import io.swagger.annotations.*; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.List; + +@Path("/pet") +@RequestScoped + +@Api(description = "the pet API") + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + +public class PetApi { + + @Context SecurityContext securityContext; + + @Inject PetApiService delegate; -@Path("/") -@Api(value = "/", description = "") -public interface PetApi { @POST @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) - public void addPet(Pet body); + @ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body) { + return delegate.addPet(body, securityContext); + } @DELETE @Path("/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Deletes a pet", tags={ "pet", }) - public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + @ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId, @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) { + return delegate.deletePet(petId, apiKey, securityContext); + } @GET @Path("/findByStatus") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) - public Pet findPetsByStatus(@QueryParam("status")List status); + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status) { + return delegate.findPetsByStatus(status, securityContext); + } @GET @Path("/findByTags") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) - public Pet findPetsByTags(@QueryParam("tags")List tags); + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags) { + return delegate.findPetsByTags(tags, securityContext); + } @GET @Path("/{petId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find pet by ID", tags={ "pet", }) - public Pet getPetById(@PathParam("petId") Long petId); + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId) { + return delegate.getPetById(petId, securityContext); + } @PUT @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Update an existing pet", tags={ "pet", }) - public void updatePet(Pet body); + @ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @ApiResponse(code = 404, message = "Pet not found", response = void.class), + @ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body) { + return delegate.updatePet(body, securityContext); + } @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) - public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status) { + return delegate.updatePetWithForm(petId, name, status, securityContext); + } @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) - @ApiOperation(value = "uploads an image", tags={ "pet" }) - public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, - @Multipart(value = "file" , required = false) Attachment fileDetail); + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail) { + return delegate.uploadFile(petId, additionalMetadata, inputStream, fileDetail, securityContext); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java index f36f46ab52c..924bf6ea7da 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java @@ -16,7 +16,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-16T23:03:38.470+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") public interface PetApiService { public Response addPet(Pet body, SecurityContext securityContext); public Response deletePet(Long petId, String apiKey, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java index b25ddf63240..9531172123c 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java @@ -2,49 +2,83 @@ package io.swagger.api; import java.util.Map; import io.swagger.model.Order; +import io.swagger.api.StoreApiService; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; import javax.ws.rs.*; +import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; -import org.apache.cxf.jaxrs.ext.multipart.*; +import io.swagger.annotations.*; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.List; + +@Path("/store") +@RequestScoped + +@Api(description = "the store API") + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + +public class StoreApi { + + @Context SecurityContext securityContext; + + @Inject StoreApiService delegate; -@Path("/") -@Api(value = "/", description = "") -public interface StoreApi { @DELETE @Path("/order/{orderId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) - public void deleteOrder(@PathParam("orderId") String orderId); + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId) { + return delegate.deleteOrder(orderId, securityContext); + } @GET @Path("/inventory") @Produces({ "application/json" }) - @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) - public Integer getInventory(); + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory() { + return delegate.getInventory(securityContext); + } @GET @Path("/order/{orderId}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) - public Order getOrderById(@PathParam("orderId") Long orderId); + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId) { + return delegate.getOrderById(orderId, securityContext); + } @POST @Path("/order") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Place an order for a pet", tags={ "store" }) - public Order placeOrder(Order body); + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body) { + return delegate.placeOrder(body, securityContext); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java index 280df1ef048..3ea40b6fbc1 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java @@ -15,7 +15,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-16T23:03:38.470+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") public interface StoreApiService { public Response deleteOrder(String orderId, SecurityContext securityContext); public Response getInventory(SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java index d05f27dba2b..cc052a69955 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java @@ -2,77 +2,126 @@ package io.swagger.api; import java.util.List; import io.swagger.model.User; +import io.swagger.api.UserApiService; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; import javax.ws.rs.*; +import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.enterprise.context.RequestScoped; +import javax.inject.Inject; -import org.apache.cxf.jaxrs.ext.multipart.*; +import io.swagger.annotations.*; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + +import java.util.List; + +@Path("/user") +@RequestScoped + +@Api(description = "the user API") + + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + +public class UserApi { + + @Context SecurityContext securityContext; + + @Inject UserApiService delegate; -@Path("/") -@Api(value = "/", description = "") -public interface UserApi { @POST @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Create user", tags={ "user", }) - public void createUser(User body); + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body) { + return delegate.createUser(body, securityContext); + } @POST @Path("/createWithArray") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithArrayInput(List body); + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body) { + return delegate.createUsersWithArrayInput(body, securityContext); + } @POST @Path("/createWithList") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithListInput(List body); + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body) { + return delegate.createUsersWithListInput(body, securityContext); + } @DELETE @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete user", tags={ "user", }) - public void deleteUser(@PathParam("username") String username); + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username) { + return delegate.deleteUser(username, securityContext); + } @GET @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", tags={ "user", }) - public User getUserByName(@PathParam("username") String username); + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username) { + return delegate.getUserByName(username, securityContext); + } @GET @Path("/login") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", tags={ "user", }) - public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password) { + return delegate.loginUser(username, password, securityContext); + } @GET @Path("/logout") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) - public void logoutUser(); + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser() { + return delegate.logoutUser(securityContext); + } @PUT @Path("/{username}") @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updated user", tags={ "user" }) - public void updateUser(@PathParam("username") String username, User body); + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + @ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, @ApiParam(value = "Updated user object" ,required=true) User body) { + return delegate.updateUser(username, body, securityContext); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java index 51ac459a415..14187d1302f 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java @@ -15,7 +15,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-16T23:03:38.470+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") public interface UserApiService { public Response createUser(User body, SecurityContext securityContext); public Response createUsersWithArrayInput(List body, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java index 7c79c18ee01..79ba2971c54 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java @@ -4,47 +4,47 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Category", propOrder = - { "id", "name" -}) +/** + * A category for a pet + **/ -@XmlRootElement(name="Category") -@ApiModel(description="A category for a pet") -public class Category { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A category for a pet") + +public class Category { - - @XmlElement(name="id") - @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="name") - @ApiModelProperty(example = "null", value = "") private String name = null; - /** - * Get id - * @return id - **/ + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - * Get name - * @return name - **/ + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") public String getName() { return name; } @@ -52,6 +52,25 @@ public class Category { this.name = name; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -67,7 +86,7 @@ public class Category { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java index e689096225b..a42de8ae1e1 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -4,61 +4,65 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "ModelApiResponse", propOrder = - { "code", "type", "message" -}) +/** + * Describes the result of uploading an image resource + **/ -@XmlRootElement(name="ModelApiResponse") -@ApiModel(description="Describes the result of uploading an image resource") -public class ModelApiResponse { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Describes the result of uploading an image resource") + +public class ModelApiResponse { - - @XmlElement(name="code") - @ApiModelProperty(example = "null", value = "") private Integer code = null; - - @XmlElement(name="type") - @ApiModelProperty(example = "null", value = "") private String type = null; - - @XmlElement(name="message") - @ApiModelProperty(example = "null", value = "") private String message = null; - /** - * Get code - * @return code - **/ + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("code") public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } - /** - * Get type - * @return type - **/ + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("type") public String getType() { return type; } public void setType(String type) { this.type = type; } - /** - * Get message - * @return message - **/ + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("message") public String getMessage() { return message; } @@ -66,6 +70,26 @@ public class ModelApiResponse { this.message = message; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -82,7 +106,7 @@ public class ModelApiResponse { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java index 59eff4f865f..d1fd9f10f03 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java @@ -4,136 +4,137 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Order", propOrder = - { "id", "petId", "quantity", "shipDate", "status", "complete" -}) +/** + * An order for a pets from the pet store + **/ -@XmlRootElement(name="Order") -@ApiModel(description="An order for a pets from the pet store") -public class Order { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "An order for a pets from the pet store") + +public class Order { - - @XmlElement(name="id") - @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="petId") - @ApiModelProperty(example = "null", value = "") private Long petId = null; - - @XmlElement(name="quantity") - @ApiModelProperty(example = "null", value = "") private Integer quantity = null; - - @XmlElement(name="shipDate") - @ApiModelProperty(example = "null", value = "") private java.util.Date shipDate = null; -@XmlType(name="StatusEnum") -@XmlEnum(String.class) -public enum StatusEnum { - - @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); - - - private String value; - - StatusEnum (String v) { - value = v; - } +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; +@XmlType(name="Order") +@XmlEnum +public enum Order { + {values=[placed, approved, delivered], enumVars=[{name=PLACED, value="placed"}, {name=APPROVED, value="approved"}, {name=DELIVERED, value="delivered"}]}, + public String value() { - return value; + return name(); } - @Override - public String toString() { - return String.valueOf(value); - } - - public static StatusEnum fromValue(String v) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(v)) { - return b; - } - } - return null; + public static Order fromValue(String v) { + return valueOf(v); } } - - - @XmlElement(name="status") - @ApiModelProperty(example = "null", value = "Order Status") private StatusEnum status = null; - - @XmlElement(name="complete") - @ApiModelProperty(example = "null", value = "") private Boolean complete = false; - /** - * Get id - * @return id - **/ + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - * Get petId - * @return petId - **/ + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("petId") public Long getPetId() { return petId; } public void setPetId(Long petId) { this.petId = petId; } - /** - * Get quantity - * @return quantity - **/ + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - * Get shipDate - * @return shipDate - **/ + + /** + **/ + public Order shipDate(java.util.Date shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("shipDate") public java.util.Date getShipDate() { return shipDate; } public void setShipDate(java.util.Date shipDate) { this.shipDate = shipDate; } - /** + + /** * Order Status - * @return status - **/ + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "Order Status") + @JsonProperty("status") public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } - /** - * Get complete - * @return complete - **/ + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("complete") public Boolean getComplete() { return complete; } @@ -141,6 +142,29 @@ public enum StatusEnum { this.complete = complete; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -160,7 +184,7 @@ public enum StatusEnum { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java index 1e3069c51f8..ebbe32b810f 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java @@ -8,136 +8,137 @@ import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Pet", propOrder = - { "id", "category", "name", "photoUrls", "tags", "status" -}) +/** + * A pet for sale in the pet store + **/ -@XmlRootElement(name="Pet") -@ApiModel(description="A pet for sale in the pet store") -public class Pet { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A pet for sale in the pet store") + +public class Pet { - - @XmlElement(name="id") - @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="category") - @ApiModelProperty(example = "null", value = "") private Category category = null; - - @XmlElement(name="name") - @ApiModelProperty(example = "doggie", required = true, value = "") private String name = null; - - @XmlElement(name="photoUrls") - @ApiModelProperty(example = "null", required = true, value = "") private List photoUrls = new ArrayList(); - - @XmlElement(name="tags") - @ApiModelProperty(example = "null", value = "") private List tags = new ArrayList(); -@XmlType(name="StatusEnum") -@XmlEnum(String.class) -public enum StatusEnum { - - @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); - - - private String value; - - StatusEnum (String v) { - value = v; - } +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlType; +@XmlType(name="Pet") +@XmlEnum +public enum Pet { + {values=[available, pending, sold], enumVars=[{name=AVAILABLE, value="available"}, {name=PENDING, value="pending"}, {name=SOLD, value="sold"}]}, + public String value() { - return value; + return name(); } - @Override - public String toString() { - return String.valueOf(value); - } - - public static StatusEnum fromValue(String v) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(v)) { - return b; - } - } - return null; + public static Pet fromValue(String v) { + return valueOf(v); } } - - - @XmlElement(name="status") - @ApiModelProperty(example = "null", value = "pet status in the store") private StatusEnum status = null; - /** - * Get id - * @return id - **/ + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - * Get category - * @return category - **/ + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("category") public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } - /** - * Get name - * @return name - **/ + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @JsonProperty("name") public String getName() { return name; } public void setName(String name) { this.name = name; } - /** - * Get photoUrls - * @return photoUrls - **/ + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - * Get tags - * @return tags - **/ + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("tags") public List getTags() { return tags; } public void setTags(List tags) { this.tags = tags; } - /** + + /** * pet status in the store - * @return status - **/ + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "pet status in the store") + @JsonProperty("status") public StatusEnum getStatus() { return status; } @@ -145,6 +146,29 @@ public enum StatusEnum { this.status = status; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -164,7 +188,7 @@ public enum StatusEnum { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java index 14bf21cebab..dc277dedce7 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java @@ -4,47 +4,47 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Tag", propOrder = - { "id", "name" -}) +/** + * A tag for a pet + **/ -@XmlRootElement(name="Tag") -@ApiModel(description="A tag for a pet") -public class Tag { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A tag for a pet") + +public class Tag { - - @XmlElement(name="id") - @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="name") - @ApiModelProperty(example = "null", value = "") private String name = null; - /** - * Get id - * @return id - **/ + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - * Get name - * @return name - **/ + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("name") public String getName() { return name; } @@ -52,6 +52,25 @@ public class Tag { this.name = name; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -67,7 +86,7 @@ public class Tag { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java index bb897ace7d6..0cc5cae6d6e 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java @@ -4,131 +4,156 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlType; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "User", propOrder = - { "id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus" -}) +/** + * A User who is purchasing from the pet store + **/ -@XmlRootElement(name="User") -@ApiModel(description="A User who is purchasing from the pet store") -public class User { +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A User who is purchasing from the pet store") + +public class User { - - @XmlElement(name="id") - @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="username") - @ApiModelProperty(example = "null", value = "") private String username = null; - - @XmlElement(name="firstName") - @ApiModelProperty(example = "null", value = "") private String firstName = null; - - @XmlElement(name="lastName") - @ApiModelProperty(example = "null", value = "") private String lastName = null; - - @XmlElement(name="email") - @ApiModelProperty(example = "null", value = "") private String email = null; - - @XmlElement(name="password") - @ApiModelProperty(example = "null", value = "") private String password = null; - - @XmlElement(name="phone") - @ApiModelProperty(example = "null", value = "") private String phone = null; - - @XmlElement(name="userStatus") - @ApiModelProperty(example = "null", value = "User Status") private Integer userStatus = null; - /** - * Get id - * @return id - **/ + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - * Get username - * @return username - **/ + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("username") public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } - /** - * Get firstName - * @return firstName - **/ + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("firstName") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } - /** - * Get lastName - * @return lastName - **/ + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("lastName") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } - /** - * Get email - * @return email - **/ + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("email") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } - /** - * Get password - * @return password - **/ + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("password") public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } - /** - * Get phone - * @return phone - **/ + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @JsonProperty("phone") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } - /** + + /** * User Status - * @return userStatus - **/ + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(example = "null", value = "User Status") + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } @@ -136,6 +161,31 @@ public class User { this.userStatus = userStatus; } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -157,7 +207,7 @@ public class User { * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private static String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java new file mode 100644 index 00000000000..1ae54938776 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java @@ -0,0 +1,9 @@ +package io.swagger.api; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class RestApplication extends Application { + // Add implementation-specific details here +} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 0c3aa88c2ab..3a03e87fc7d 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,72 +1,63 @@ package io.swagger.api.impl; import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + import java.io.File; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; -import java.io.InputStream; -import java.io.OutputStream; import java.util.List; -import java.util.Map; -import javax.ws.rs.*; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; +import javax.ws.rs.core.SecurityContext; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class PetApiServiceImpl implements PetApi { - public void addPet(Pet body) { - // TODO: Implement... - - - } - - public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey) { - // TODO: Implement... - - - } - - public Pet findPetsByStatus(List status) { - // TODO: Implement... - - return null; - } - - public Pet findPetsByTags(List tags) { - // TODO: Implement... - - return null; - } - - public Pet getPetById(@PathParam("petId") Long petId) { - // TODO: Implement... - - return null; - } - - public void updatePet(Pet body) { - // TODO: Implement... - - - } - - public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status) { - // TODO: Implement... - - - } - - public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, - @Multipart(value = "file" , required = false) Attachment fileDetail) { - // TODO: Implement... - - return null; - } - +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") +public class PetApiServiceImpl implements PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response findPetsByStatus(List status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response findPetsByTags(List tags, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, Attachment fileDetail, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 4e36fd37d70..fed0fa6c0f0 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,46 +1,42 @@ package io.swagger.api.impl; import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + import java.util.Map; import io.swagger.model.Order; -import java.io.InputStream; -import java.io.OutputStream; import java.util.List; -import java.util.Map; -import javax.ws.rs.*; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; +import javax.ws.rs.core.SecurityContext; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class StoreApiServiceImpl implements StoreApi { - public void deleteOrder(@PathParam("orderId") String orderId) { - // TODO: Implement... - - - } - - public Integer getInventory() { - // TODO: Implement... - - return null; - } - - public Order getOrderById(@PathParam("orderId") Long orderId) { - // TODO: Implement... - - return null; - } - - public Order placeOrder(Order body) { - // TODO: Implement... - - return null; - } - +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") +public class StoreApiServiceImpl implements StoreApiService { + @Override + public Response deleteOrder(String orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getInventory(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getOrderById(Long orderId, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index dff57676b6f..4f4b3db2382 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,70 +1,62 @@ package io.swagger.api.impl; import io.swagger.api.*; +import io.swagger.model.*; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; + import java.util.List; import io.swagger.model.User; -import java.io.InputStream; -import java.io.OutputStream; import java.util.List; -import java.util.Map; -import javax.ws.rs.*; + +import java.io.InputStream; + +import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; -import org.apache.cxf.jaxrs.model.wadl.Description; -import org.apache.cxf.jaxrs.model.wadl.DocTarget; +import javax.ws.rs.core.SecurityContext; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; - -public class UserApiServiceImpl implements UserApi { - public void createUser(User body) { - // TODO: Implement... - - - } - - public void createUsersWithArrayInput(List body) { - // TODO: Implement... - - - } - - public void createUsersWithListInput(List body) { - // TODO: Implement... - - - } - - public void deleteUser(@PathParam("username") String username) { - // TODO: Implement... - - - } - - public User getUserByName(@PathParam("username") String username) { - // TODO: Implement... - - return null; - } - - public String loginUser(String username, String password) { - // TODO: Implement... - - return null; - } - - public void logoutUser() { - // TODO: Implement... - - - } - - public void updateUser(@PathParam("username") String username, User body) { - // TODO: Implement... - - - } - +@RequestScoped +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") +public class UserApiServiceImpl implements UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response loginUser(String username, String password, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) { + // do some magic! + return Response.ok().entity("magic!").build(); + } } - diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml b/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml new file mode 100644 index 00000000000..cb6d500d43f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml @@ -0,0 +1,13 @@ + + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json index 83b9214c608..f48e38d5cb2 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json +++ b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json @@ -637,11 +637,6 @@ } }, "securityDefinitions" : { - "api_key" : { - "type" : "apiKey", - "name" : "api_key", - "in" : "header" - }, "petstore_auth" : { "type" : "oauth2", "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", @@ -650,6 +645,11 @@ "write:pets" : "modify pets in your account", "read:pets" : "read your pets" } + }, + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" } }, "definitions" : { From 5baa71560346f1c152ee06160ced4710c37565bd Mon Sep 17 00:00:00 2001 From: James Hitchcock Date: Fri, 18 Nov 2016 07:16:35 +0100 Subject: [PATCH 072/269] Remove opening PHP tag from PHP code sample (#4212) --- .../src/main/resources/htmlDocs2/sample_php.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache index bb589426f81..4b9ee43b866 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache @@ -1,4 +1,4 @@ - Date: Fri, 18 Nov 2016 07:21:17 +0100 Subject: [PATCH 073/269] fix(swift3): rename reserved enum values (#4201) Example: - case public = "public" + case _public = "public" Signed-off-by: Vincent Giersch --- .../codegen/languages/Swift3Codegen.java | 5 + .../Classes/Swaggers/APIs/FakeAPI.swift | 4 +- .../Classes/Swaggers/APIs/PetAPI.swift | 152 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 60 +++---- .../Classes/Swaggers/APIs/UserAPI.swift | 44 ++--- .../Classes/Swaggers/APIs/FakeAPI.swift | 4 +- .../Classes/Swaggers/APIs/PetAPI.swift | 152 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 60 +++---- .../Classes/Swaggers/APIs/UserAPI.swift | 44 ++--- .../Classes/Swaggers/APIs/FakeAPI.swift | 4 +- .../Classes/Swaggers/APIs/PetAPI.swift | 152 +++++++++--------- .../Classes/Swaggers/APIs/StoreAPI.swift | 60 +++---- .../Classes/Swaggers/APIs/UserAPI.swift | 44 ++--- 13 files changed, 395 insertions(+), 390 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index d08dd89c585..7bfdbf10e07 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -506,6 +506,11 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); } + // Reserved Name + if (isReservedWord(name)) { + return escapeReservedWord(name); + } + if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { String varName = "number" + camelize(name); diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 8a3f0796cdf..7ff3c6e4202 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -26,9 +26,9 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake - - examples: [{example={ + - examples: [{contentType=application/json, example={ "client" : "aeiou" -}, contentType=application/json}] +}}] - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 06e868f881e..0588a85ade1 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -117,7 +117,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -126,21 +126,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -149,20 +149,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter status: (query) Status values that need to be considered for filter @@ -205,7 +205,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -214,21 +214,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -237,20 +237,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter tags: (query) Tags to filter by @@ -293,7 +293,7 @@ open class PetAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -302,21 +302,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -325,20 +325,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] - parameter petId: (path) ID of pet to return @@ -467,11 +467,11 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "message" : "aeiou", + - examples: [{contentType=application/json, example={ "code" : 123, - "type" : "aeiou" -}, contentType=application/json}] + "type" : "aeiou", + "message" : "aeiou" +}}] - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index d5b2aede9c0..8c30504c5c9 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,9 +67,9 @@ open class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}] +}}] - returns: RequestBuilder<[String:Int32]> */ @@ -105,36 +105,36 @@ open class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -173,36 +173,36 @@ open class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter body: (body) order placed for purchasing the pet diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 9aec457645a..84ba24276e2 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,7 +167,7 @@ open class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 string string @@ -176,17 +176,17 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] - - examples: [{example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 string string @@ -195,16 +195,16 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -246,8 +246,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index dff3efee6a7..407320d315c 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -44,9 +44,9 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake - - examples: [{example={ + - examples: [{contentType=application/json, example={ "client" : "aeiou" -}, contentType=application/json}] +}}] - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 287d11d4e6d..48a7379ca26 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -169,7 +169,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -178,21 +178,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -201,20 +201,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter status: (query) Status values that need to be considered for filter @@ -274,7 +274,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -283,21 +283,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -306,20 +306,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter tags: (query) Tags to filter by @@ -379,7 +379,7 @@ open class PetAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -388,21 +388,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -411,20 +411,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] - parameter petId: (path) ID of pet to return @@ -608,11 +608,11 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "message" : "aeiou", + - examples: [{contentType=application/json, example={ "code" : 123, - "type" : "aeiou" -}, contentType=application/json}] + "type" : "aeiou", + "message" : "aeiou" +}}] - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 11a63055877..dac3b79dcbe 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -101,9 +101,9 @@ open class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}] +}}] - returns: RequestBuilder<[String:Int32]> */ @@ -156,36 +156,36 @@ open class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -241,36 +241,36 @@ open class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter body: (body) order placed for purchasing the pet diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index bd000b1297e..84557cffcb2 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -253,7 +253,7 @@ open class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 string string @@ -262,17 +262,17 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] - - examples: [{example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 string string @@ -281,16 +281,16 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -350,8 +350,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 1edf39d3062..69dab9ff57b 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -46,9 +46,9 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake - - examples: [{example={ + - examples: [{contentType=application/json, example={ "client" : "aeiou" -}, contentType=application/json}] +}}] - parameter body: (body) client model diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 845a950ce6d..e5c3f5e3325 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -175,7 +175,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -184,21 +184,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -207,20 +207,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter status: (query) Status values that need to be considered for filter @@ -282,7 +282,7 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -291,21 +291,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -314,20 +314,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}] - parameter tags: (query) Tags to filter by @@ -389,7 +389,7 @@ open class PetAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 doggie @@ -398,21 +398,21 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] - - examples: [{example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 doggie @@ -421,20 +421,20 @@ open class PetAPI: APIBase { string -, contentType=application/xml}, {example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}, {contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}] + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}] - parameter petId: (path) ID of pet to return @@ -624,11 +624,11 @@ open class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "message" : "aeiou", + - examples: [{contentType=application/json, example={ "code" : 123, - "type" : "aeiou" -}, contentType=application/json}] + "type" : "aeiou", + "message" : "aeiou" +}}] - parameter petId: (path) ID of pet to update - parameter additionalMetadata: (form) Additional data to pass to server (optional) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 791070dea5e..4b27503475b 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -105,9 +105,9 @@ open class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}] +}}] - returns: RequestBuilder<[String:Int32]> */ @@ -162,36 +162,36 @@ open class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -249,36 +249,36 @@ open class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] - - examples: [{example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}, {example={ - "id" : 123456789, +}, {contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}] + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}] - parameter body: (body) order placed for purchasing the pet diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index c0cab158525..a6530489f39 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -263,7 +263,7 @@ open class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example= + - examples: [{contentType=application/xml, example= 123456 string string @@ -272,17 +272,17 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] - - examples: [{example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] + - examples: [{contentType=application/xml, example= 123456 string string @@ -291,16 +291,16 @@ open class UserAPI: APIBase { string string 0 -, contentType=application/xml}, {example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}, {contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}] + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -362,8 +362,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] - - examples: [{example=string, contentType=application/xml}, {example="aeiou", contentType=application/json}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text From da136135af07bcb8c01826d6179693fa17e49ef5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 18 Nov 2016 16:46:54 +0800 Subject: [PATCH 074/269] add http://www.intenthq.com --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a934a3c3cec..613940bddd1 100644 --- a/README.md +++ b/README.md @@ -773,6 +773,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [GraphHopper](https://graphhopper.com/) - [Gravitate Solutions](http://gravitatesolutions.com/) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) +- [Intent HQ](http://www.intenthq.com) - [Interactive Intelligence](http://developer.mypurecloud.com/) - [LANDR Audio](https://www.landr.com/) - [Lascaux](http://www.lascaux.it/) From a260636a48d6b49852568986cac2eef14671475f Mon Sep 17 00:00:00 2001 From: RaphC Date: Fri, 18 Nov 2016 09:52:42 +0100 Subject: [PATCH 075/269] #3908 make a copy of vendorExtensions map instead of copying the reference (#4093) * #3908 make a copy of vendorExtensions map instead of copying the reference * using 4-space instead of tab. * make a copy of vendorExtensions map instead of copying the reference --- .../io/swagger/codegen/CodegenParameter.java | 4 +++- .../io/swagger/codegen/CodegenProperty.java | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index 98770029381..c282fb519a2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -122,7 +122,9 @@ public class CodegenParameter { if (this.items != null) { output.items = this.items; } - output.vendorExtensions = this.vendorExtensions; + if(this.vendorExtensions != null){ + output.vendorExtensions = new HashMap(this.vendorExtensions); + } output.hasValidation = this.hasValidation; output.isBinary = this.isBinary; output.isByteArray = this.isByteArray; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index b6a4b9d02da..66995f8d118 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -1,5 +1,7 @@ package io.swagger.codegen; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; @@ -283,9 +285,24 @@ public class CodegenProperty implements Cloneable { @Override public CodegenProperty clone() { try { - return (CodegenProperty) super.clone(); + CodegenProperty cp = (CodegenProperty) super.clone(); + if (this._enum != null) { + cp._enum = new ArrayList(this._enum); + } + if (this.allowableValues != null) { + cp.allowableValues = new HashMap(this.allowableValues); + } + if (this.items != null) { + cp.items = this.items; + } + if(this.vendorExtensions != null){ + cp.vendorExtensions = new HashMap(this.vendorExtensions); + } + return cp; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } + + } From 9c6fbad73d7b221ce11f5a4f93558eae464fe724 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 19 Nov 2016 00:03:57 +0800 Subject: [PATCH 076/269] add Flat (https://flat.io) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 613940bddd1..fe693c57f37 100644 --- a/README.md +++ b/README.md @@ -765,6 +765,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) +- [Flat](https://flat.io) - [Finder](http://en.finder.pl/) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) - [Gear Zero Network](https://www.gearzero.ca) From 0a5b0bb8ce77a391bce1843a5193fa7a13efa7e4 Mon Sep 17 00:00:00 2001 From: www2k Date: Mon, 31 Oct 2016 01:04:24 +0900 Subject: [PATCH 077/269] Add test for file response schema --- .../java/io/swagger/codegen/CodegenTest.java | 15 ++++++++- .../test/resources/2_0/fileResponseTest.json | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/fileResponseTest.json diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 37050a1be4b..5848108055d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -43,7 +43,7 @@ public class CodegenTest { final CodegenParameter file = op.formParams.get(1); Assert.assertTrue(file.isFormParam); - Assert.assertEquals(file.dataType, "file"); + Assert.assertEquals(file.dataType, "File"); Assert.assertNull(file.required); Assert.assertTrue(file.isFile); Assert.assertNull(file.hasMore); @@ -187,6 +187,19 @@ public class CodegenTest { Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); } + + @Test(description = "return file when response format is file") + public void fileResponeseTest() { + final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/fileResponseTest.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/fileResponse"; + final Operation p = model.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "File"); + Assert.assertTrue(op.responses.get(0).isFile); + Assert.assertTrue(op.isResponseFile); + } @Test(description = "discriminator is present") public void discriminatorTest() { diff --git a/modules/swagger-codegen/src/test/resources/2_0/fileResponseTest.json b/modules/swagger-codegen/src/test/resources/2_0/fileResponseTest.json new file mode 100644 index 00000000000..ab8237934ef --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/fileResponseTest.json @@ -0,0 +1,33 @@ +{ + "swagger": "2.0", + "info": { + "version": "1.0.0", + "title": "File Response Test", + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/tests/fileResponse": { + "get": { + "operationId": "fileresponsetest", + "produces": [ + "application/octet-stream" + ], + "responses": { + "200": { + "description": "OutputFileData", + "schema": { + "type": "file" + } + } + } + } + } + } +} From e14be8bab9dec40425f7c69390a45f7d8fe22c02 Mon Sep 17 00:00:00 2001 From: www2k Date: Mon, 31 Oct 2016 01:13:21 +0900 Subject: [PATCH 078/269] Support file response schema --- .../io/swagger/codegen/CodegenOperation.java | 5 ++++- .../io/swagger/codegen/CodegenProperty.java | 6 +++++- .../io/swagger/codegen/CodegenResponse.java | 4 ++++ .../io/swagger/codegen/DefaultCodegen.java | 21 +++++++++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 1bd02c68d5d..d9f4f1f3aae 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -14,7 +14,7 @@ public class CodegenOperation { public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, isMultipart, hasMore = Boolean.TRUE, - isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, + isResponseBinary = Boolean.FALSE, isResponseFile = Boolean.FALSE, hasReference = Boolean.FALSE, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, @@ -215,6 +215,8 @@ public class CodegenOperation { return false; if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null) return false; + if (isResponseFile != null ? !isResponseFile.equals(that.isResponseFile) : that.isResponseFile != null) + return false; if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null) return false; if (path != null ? !path.equals(that.path) : that.path != null) @@ -297,6 +299,7 @@ public class CodegenOperation { result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0); result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0); result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0); + result = 31 * result + (isResponseFile != null ? isResponseFile.hashCode() : 0); result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (operationId != null ? operationId.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 66995f8d118..9b617d13fae 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -37,7 +37,7 @@ public class CodegenProperty implements Cloneable { public Boolean hasMore, required, secondaryParam; public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly public Boolean isPrimitiveType, isContainer, isNotContainer; - public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; + public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime; public Boolean isListContainer, isMapContainer; public boolean isEnum; public Boolean isReadOnly = false; @@ -108,6 +108,7 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((isDouble == null) ? 0 : isDouble.hashCode()); result = prime * result + ((isByteArray == null) ? 0 : isByteArray.hashCode()); result = prime * result + ((isBinary == null) ? 0 : isBinary.hashCode()); + result = prime * result + ((isFile == null) ? 0 : isFile.hashCode()); result = prime * result + ((isBoolean == null) ? 0 : isBoolean.hashCode()); result = prime * result + ((isDate == null) ? 0 : isDate.hashCode()); result = prime * result + ((isDateTime == null) ? 0 : isDateTime.hashCode()); @@ -264,6 +265,9 @@ public class CodegenProperty implements Cloneable { if (this.isBinary != other.isBinary && (this.isBinary == null || !this.isBinary.equals(other.isBinary))) { return false; } + if (this.isFile != other.isFile && (this.isFile == null || !this.isFile.equals(other.isFile))) { + return false; + } if (this.isListContainer != other.isListContainer && (this.isListContainer == null || !this.isListContainer.equals(other.isListContainer))) { return false; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index a8a2117a31e..fb09f820be5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -16,6 +16,7 @@ public class CodegenResponse { public Boolean isMapContainer; public Boolean isListContainer; public Boolean isBinary = Boolean.FALSE; + public Boolean isFile = Boolean.FALSE; public Object schema; public String jsonSchema; @@ -63,6 +64,8 @@ public class CodegenResponse { return false; if (isBinary != null ? !isBinary.equals(that.isBinary) : that.isBinary != null) return false; + if (isFile != null ? !isFile.equals(that.isFile) : that.isFile != null) + return false; if (schema != null ? !schema.equals(that.schema) : that.schema != null) return false; return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; @@ -85,6 +88,7 @@ public class CodegenResponse { result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0); result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0); result = 31 * result + (isBinary != null ? isBinary.hashCode() : 0); + result = 31 * result + (isFile != null ? isFile.hashCode() : 0); result = 31 * result + (schema != null ? schema.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); return result; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 5ccc9b24945..e9894547369 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -36,6 +36,7 @@ import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateTimeProperty; import io.swagger.models.properties.DecimalProperty; import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.FileProperty; import io.swagger.models.properties.FloatProperty; import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; @@ -765,6 +766,7 @@ public class DefaultCodegen { typeMapping.put("integer", "Integer"); typeMapping.put("ByteArray", "byte[]"); typeMapping.put("binary", "byte[]"); + typeMapping.put("file", "File"); instantiationTypes = new HashMap(); @@ -1069,6 +1071,8 @@ public class DefaultCodegen { datatype = "ByteArray"; } else if (p instanceof BinaryProperty) { datatype = "binary"; + } else if (p instanceof FileProperty) { + datatype = "file"; } else if (p instanceof BooleanProperty) { datatype = "boolean"; } else if (p instanceof DateProperty) { @@ -1536,6 +1540,9 @@ public class DefaultCodegen { if (p instanceof BinaryProperty) { property.isBinary = true; } + if (p instanceof FileProperty) { + property.isFile = true; + } if (p instanceof UUIDProperty) { property.isString = true; } @@ -1964,6 +1971,9 @@ public class DefaultCodegen { if (r.isBinary && r.isDefault){ op.isResponseBinary = Boolean.TRUE; } + if (r.isFile && r.isDefault){ + op.isResponseFile = Boolean.TRUE; + } } op.responses.get(op.responses.size() - 1).hasMore = false; @@ -2163,6 +2173,7 @@ public class DefaultCodegen { } r.dataType = cm.datatype; r.isBinary = isDataTypeBinary(cm.datatype); + r.isFile = isDataTypeFile(cm.datatype); if (cm.isContainer != null) { r.simpleType = false; r.containerType = cm.containerType; @@ -2345,6 +2356,7 @@ public class DefaultCodegen { p.dataType = cp.datatype; p.isPrimitiveType = cp.isPrimitiveType; p.isBinary = isDataTypeBinary(cp.datatype); + p.isFile = isDataTypeFile(cp.datatype); } // set boolean flag (e.g. isString) @@ -2412,6 +2424,8 @@ public class DefaultCodegen { p.example = "BINARY_DATA_HERE"; } else if (Boolean.TRUE.equals(p.isByteArray)) { p.example = "B"; + } else if (Boolean.TRUE.equals(p.isFile)) { + p.example = "/path/to/file.txt"; } else if (Boolean.TRUE.equals(p.isDate)) { p.example = "2013-10-20"; } else if (Boolean.TRUE.equals(p.isDateTime)) { @@ -2462,6 +2476,10 @@ public class DefaultCodegen { return dataType.toLowerCase().startsWith("byte"); } + public boolean isDataTypeFile(String dataType) { + return dataType.toLowerCase().equals("file"); + } + /** * Convert map of Swagger SecuritySchemeDefinition objects to a list of Codegen Security objects * @@ -3257,6 +3275,9 @@ public class DefaultCodegen { } else if (Boolean.TRUE.equals(property.isBinary)) { parameter.isByteArray = true; parameter.isPrimitiveType = true; + } else if (Boolean.TRUE.equals(property.isFile)) { + parameter.isFile = true; + parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDate)) { parameter.isDate = true; parameter.isPrimitiveType = true; From ed1b6075e977cd2fb812d0509d2c9d0d3da86657 Mon Sep 17 00:00:00 2001 From: www2k Date: Mon, 31 Oct 2016 01:59:19 +0900 Subject: [PATCH 079/269] Add file response support for typescript-node --- .../languages/TypeScriptNodeClientCodegen.java | 17 +++++++++++++++++ .../main/resources/typescript-node/api.mustache | 5 +++++ 2 files changed, 22 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 67a6ed0b422..50662a26dd5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,5 +1,7 @@ package io.swagger.codegen.languages; +import io.swagger.models.properties.FileProperty; +import io.swagger.models.properties.Property; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -27,6 +29,8 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen public TypeScriptNodeClientCodegen() { super(); + typeMapping.put("file", "Buffer"); + // clear import mapping (from default generator) as TS does not use it // at the moment importMapping.clear(); @@ -92,6 +96,19 @@ public class TypeScriptNodeClientCodegen extends AbstractTypeScriptClientCodegen return "Generates a TypeScript nodejs client library."; } + @Override + public boolean isDataTypeFile(final String dataType) { + return dataType != null && dataType.equals("Buffer"); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof FileProperty) { + return "Buffer"; + } + return super.getTypeDeclaration(p); + } + public void setNpmName(String npmName) { this.npmName = npmName; 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 d501432df28..8817a657fa4 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -235,7 +235,12 @@ export class {{classname}} { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, +{{^isResponseFile}} json: true, +{{/isResponseFile}} +{{#isResponseFile}} + encoding: null, +{{/isResponseFile}} {{#bodyParam}} body: {{paramName}}, {{/bodyParam}} From 7a7eb113b3c32c48269ca74052137c8bd1fbd9ee Mon Sep 17 00:00:00 2001 From: Chester Husk III Date: Sat, 19 Nov 2016 01:50:22 -0600 Subject: [PATCH 080/269] address unused parameters and possible-nullity warnings (#4210) * address unused parameters and possible-nullity warnings that newer versions of typescript give for this file * update example generated clients using the new nullability code --- .../resources/typescript-node/api.mustache | 8 +++-- .../petstore/typescript-node/default/api.ts | 32 ++++++++++++++++--- .../petstore/typescript-node/npm/api.ts | 32 ++++++++++++++++--- 3 files changed, 59 insertions(+), 13 deletions(-) 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 d501432df28..cf6040ae3eb 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -75,7 +75,7 @@ export class ApiKeyAuth implements Authentication { applyToRequest(requestOptions: request.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; - } else if (this.location == "header") { + } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } @@ -85,14 +85,16 @@ export class OAuth implements Authentication { public accessToken: string; applyToRequest(requestOptions: request.Options): void { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + if (requestOptions && requestOptions.headers) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } } } export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(_: request.Options): void { // Do nothing } } diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 0b56af22d28..9deaabf6d00 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -111,7 +111,7 @@ export class ApiKeyAuth implements Authentication { applyToRequest(requestOptions: request.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; - } else if (this.location == "header") { + } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } @@ -121,14 +121,16 @@ export class OAuth implements Authentication { public accessToken: string; applyToRequest(requestOptions: request.Options): void { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + if (requestOptions && requestOptions.headers) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } } } export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(_: request.Options): void { // Do nothing } } @@ -200,6 +202,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -258,6 +261,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -310,6 +314,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -362,6 +367,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -416,13 +422,14 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -466,6 +473,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -531,6 +539,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -596,6 +605,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -698,6 +708,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -743,6 +754,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -797,6 +809,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -843,6 +856,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -938,6 +952,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -985,6 +1000,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -1032,6 +1048,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -1085,6 +1102,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1137,6 +1155,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1192,6 +1211,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1237,6 +1257,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1290,6 +1311,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index 0b56af22d28..9deaabf6d00 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -111,7 +111,7 @@ export class ApiKeyAuth implements Authentication { applyToRequest(requestOptions: request.Options): void { if (this.location == "query") { (requestOptions.qs)[this.paramName] = this.apiKey; - } else if (this.location == "header") { + } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } @@ -121,14 +121,16 @@ export class OAuth implements Authentication { public accessToken: string; applyToRequest(requestOptions: request.Options): void { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + if (requestOptions && requestOptions.headers) { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } } } export class VoidAuth implements Authentication { public username: string; public password: string; - applyToRequest(requestOptions: request.Options): void { + applyToRequest(_: request.Options): void { // Do nothing } } @@ -200,6 +202,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -258,6 +261,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -310,6 +314,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -362,6 +367,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -416,13 +422,14 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -466,6 +473,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -531,6 +539,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -596,6 +605,7 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -698,6 +708,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -743,6 +754,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -797,6 +809,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -843,6 +856,7 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -938,6 +952,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -985,6 +1000,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -1032,6 +1048,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; @@ -1085,6 +1102,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1137,6 +1155,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1192,6 +1211,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1237,6 +1257,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, }; @@ -1290,6 +1311,7 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, + json: true, body: body, }; From 95ac23802635d4ab9f954ab0277f1903833aafca Mon Sep 17 00:00:00 2001 From: Chester Husk III Date: Sat, 19 Nov 2016 01:51:14 -0600 Subject: [PATCH 081/269] [Typescript] Add Error to the list of reserved words that must be escaped (#4203) * Add Error to the list of reserved words that must be escaped for Class-generation This fixes a part of #2456. * add in special casing for the model names to not clobber existing language type names * address formatting issues to be in line with language convention --- .../languages/AbstractTypeScriptClientCodegen.java | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 71f7d32c5eb..9322af82e95 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -55,7 +55,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp "Array", "Date", "number", - "any" + "any", + "Error" )); instantiationTypes.put("array", "Array"); @@ -174,6 +175,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return modelName; } + if (languageSpecificPrimitives.contains(name)) { + String modelName = camelize("model_" + name); + LOGGER.warn(name + " (model name matches existing language type) cannot be used as a model name. Renamed to " + modelName); + return modelName; + } // camelize the model name // phone_number => PhoneNumber return camelize(name); From b02d505ad9322812af5194fcb1fd49a5a51c69a1 Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 19 Nov 2016 09:09:13 +0100 Subject: [PATCH 082/269] Refine CXF Add Spring Annotation-Config + Jboss flag for CXF/Resteasy + fix OuterEnum (#4164) * add json annotations * add cli flag to check for jaxb annotations * add CLI-flag for switching Spring-XML or annotation config #4088 * add cli flag for generating jboss depl. descriptor #4088 * add JbossFeature CLI flag to Resteasy #4088 * update/add tests #4088 * cleanup tabs #4088 * improve api formatting #4088 * refine formatting #4088 * refine formatting again #4088 * add separate CLI-flags for controlling junit test features #4088 * add json annotations * add cli flag to check for jaxb annotations * add CLI-flag for switching Spring-XML or annotation config #4088 * add cli flag for generating jboss depl. descriptor #4088 * add JbossFeature CLI flag to Resteasy #4088 * update/add tests #4088 * cleanup tabs #4088 * improve api formatting #4088 * refine formatting #4088 * refine formatting again #4088 * add separate CLI-flags for controlling junit test features #4088 * add check for void methods + assertNotNull(response) #4088 * add spaces for @Produces #4088 * allow build with no web.xml config #4088 * comment invocations of tests #4088 * update petstore sample jaxrs-cxf server with gen/java first #4088 * re-generate jaxrs-cxf with src/gen/java #4088 * add client jaxrs-cxf #4088 * add switch to load SwaggerUI automatically #4088 * update to CXF 3.1.8 including supportSwaggerUi flag #4088 * update to cxf 3.1.8 and swagger-core 1.5.10 #4088 * update generated petstore for jaxrs-cxf #4088 * change Spring Boot urls to root #4088 * fix spring xml config #4088 * fix external enum usage for jaxrs-cxf #4160 * cleanup jaxrs-annotations in impl class * fix handling of multiparts #4088 * fix @Min/@Max comments in beanValidationQueryParams #4088 * add swagger-codegen-ignore file+add src/test/resources #4088 * add cli-flag for produces/consumes json in api #4088 * add test case for outerEnum #4160 --- .../AbstractJavaJAXRSServerCodegen.java | 1 + .../languages/JavaCXFClientCodegen.java | 55 ++--- .../languages/JavaCXFServerCodegen.java | 106 ++++++++- .../languages/JavaResteasyServerCodegen.java | 24 +- .../languages/features/CXFFeatures.java | 4 +- .../languages/features/CXFServerFeatures.java | 41 ++-- .../languages/features/GzipFeatures.java | 2 +- .../languages/features/GzipTestFeatures.java | 9 + .../languages/features/JaxbFeatures.java | 7 + .../languages/features/JbossFeature.java | 9 + .../features/LoggingTestFeatures.java | 8 + .../languages/features/SpringFeatures.java | 4 + .../languages/features/SwaggerUIFeatures.java | 9 + .../main/resources/JavaJaxRS/cxf/api.mustache | 80 ++++--- .../JavaJaxRS/cxf/apiServiceImpl.mustache | 8 +- .../resources/JavaJaxRS/cxf/api_test.mustache | 19 +- .../cxf/beanValidationQueryParams.mustache | 1 + .../JavaJaxRS/cxf/enumOuterClass.mustache | 43 ++++ .../JavaJaxRS/cxf/formParams.mustache | 3 +- .../JavaJaxRS/cxf/formParamsImpl.mustache | 1 + .../JavaJaxRS/cxf/headerParamsImpl.mustache | 1 + .../resources/JavaJaxRS/cxf/model.mustache | 2 +- .../JavaJaxRS/cxf/pathParamsImpl.mustache | 1 + .../resources/JavaJaxRS/cxf/pojo.mustache | 5 +- .../JavaJaxRS/cxf/queryParams.mustache | 2 +- .../server/ApplicationContext.xml.mustache | 15 +- .../server/application.properties.mustache | 1 + .../JavaJaxRS/cxf/server/pom.mustache | 13 +- .../resources/JavaJaxRS/cxf/server/readme.md | 13 ++ .../server/swagger-codegen-ignore.mustache | 25 ++ .../jaxrs/JavaResteasyServerOptionsTest.java | 67 ++++++ .../jaxrs/JaxrsCXFClientOptionsTest.java | 74 ++++++ .../jaxrs/JaxrsCXFServerOptionsTest.java | 188 ++++++++------- .../options/JavaCXFClientOptionsProvider.java | 47 ++++ .../options/JavaCXFServerOptionsProvider.java | 156 +++++++------ .../JavaResteasyServerOptionsProvider.java | 42 ++++ ...ith-fake-endpoints-models-for-testing.yaml | 9 + .../jaxrs-cxf/.swagger-codegen-ignore | 23 ++ samples/client/petstore/jaxrs-cxf/LICENSE | 201 ++++++++++++++++ samples/client/petstore/jaxrs-cxf/pom.xml | 162 +++++++++++++ .../src/gen/java/io/swagger/api/PetApi.java | 78 +++++++ .../src/gen/java/io/swagger/api/StoreApi.java | 47 ++++ .../src/gen/java/io/swagger/api/UserApi.java | 71 ++++++ .../gen/java/io/swagger/model/Category.java | 28 +-- .../io/swagger/model/ModelApiResponse.java | 38 ++- .../src}/gen/java/io/swagger/model/Order.java | 67 +++--- .../src}/gen/java/io/swagger/model/Pet.java | 67 +++--- .../src}/gen/java/io/swagger/model/Tag.java | 28 +-- .../src}/gen/java/io/swagger/model/User.java | 87 ++++--- .../test/java/io/swagger/api/PetApiTest.java | 205 ++++++++++++++++ .../java/io/swagger/api/StoreApiTest.java | 133 +++++++++++ .../test/java/io/swagger/api/UserApiTest.java | 199 ++++++++++++++++ .../gen/java/io/swagger/api/PetApi.java | 60 ----- .../gen/java/io/swagger/api/StoreApi.java | 38 --- .../gen/java/io/swagger/api/UserApi.java | 58 ----- samples/server/petstore/jaxrs-cxf/pom.xml | 6 +- .../src/gen/java/io/swagger/api/PetApi.java | 77 ++++++ .../src/gen/java/io/swagger/api/StoreApi.java | 48 ++++ .../src/gen/java/io/swagger/api/UserApi.java | 72 ++++++ .../gen/java/io/swagger/model/Category.java | 65 ++++++ .../io/swagger/model/ModelApiResponse.java | 78 +++++++ .../src/gen/java/io/swagger/model/Order.java | 150 ++++++++++++ .../src/gen/java/io/swagger/model/Pet.java | 154 ++++++++++++ .../src/gen/java/io/swagger/model/Tag.java | 65 ++++++ .../src/gen/java/io/swagger/model/User.java | 143 ++++++++++++ .../swagger/api/impl/PetApiServiceImpl.java | 71 ++++++ .../swagger/api/impl/StoreApiServiceImpl.java | 46 ++++ .../swagger/api/impl/UserApiServiceImpl.java | 70 ++++++ .../test/java/io/swagger/api/PetApiTest.java | 221 ++++++++++++++++++ .../java/io/swagger/api/StoreApiTest.java | 142 +++++++++++ .../test/java/io/swagger/api/UserApiTest.java | 216 +++++++++++++++++ 71 files changed, 3719 insertions(+), 590 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipTestFeatures.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JaxbFeatures.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingTestFeatures.java create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SwaggerUIFeatures.java create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParamsImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParamsImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/application.properties.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxrsCXFClientOptionsTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFClientOptionsProvider.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java create mode 100644 samples/client/petstore/jaxrs-cxf/.swagger-codegen-ignore create mode 100644 samples/client/petstore/jaxrs-cxf/LICENSE create mode 100644 samples/client/petstore/jaxrs-cxf/pom.xml create mode 100644 samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java create mode 100644 samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java create mode 100644 samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/Category.java (82%) rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/ModelApiResponse.java (79%) rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/Order.java (81%) rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/Pet.java (81%) rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/Tag.java (82%) rename samples/{server/petstore/jaxrs-cxf => client/petstore/jaxrs-cxf/src}/gen/java/io/swagger/model/User.java (75%) create mode 100644 samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java create mode 100644 samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java create mode 100644 samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java delete mode 100644 samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java delete mode 100644 samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java delete mode 100644 samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java create mode 100644 samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index af961e9983b..08410c47d44 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -17,6 +17,7 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen */ protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; protected String implFolder = "src/main/java"; + protected String testResourcesFolder = "src/test/resources"; protected String title = "Swagger Server"; static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java index 15bf08191a5..d1c9d41ae31 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFClientCodegen.java @@ -14,11 +14,14 @@ import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.SupportingFile; -import io.swagger.codegen.languages.features.CXFFeatures; -import io.swagger.codegen.languages.features.LoggingFeatures; +import io.swagger.codegen.languages.features.BeanValidationFeatures; +import io.swagger.codegen.languages.features.GzipTestFeatures; +import io.swagger.codegen.languages.features.JaxbFeatures; +import io.swagger.codegen.languages.features.LoggingTestFeatures; import io.swagger.models.Operation; -public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeatures +public class JavaCXFClientCodegen extends AbstractJavaCodegen + implements BeanValidationFeatures, JaxbFeatures, GzipTestFeatures, LoggingTestFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFClientCodegen.class); @@ -28,14 +31,13 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat */ protected static final String JAXRS_TEMPLATE_DIRECTORY_NAME = "JavaJaxRS"; + protected boolean useJaxbAnnotations = true; + protected boolean useBeanValidation = false; - protected boolean useGzipFeature = false; - - protected boolean useLoggingFeature = false; - - protected boolean useBeanValidationFeature = false; + protected boolean useGzipFeatureForTests = false; + protected boolean useLoggingFeatureForTests = false; public JavaCXFClientCodegen() { @@ -67,11 +69,12 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; + cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); - cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Use Gzip Feature")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature")); - cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature")); + cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests")); + cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests")); } @@ -82,19 +85,19 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat { super.processOpts(); + if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) { + boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); + this.setUseJaxbAnnotations(useJaxbAnnotationsProp); + } + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); this.setUseBeanValidation(useBeanValidationProp); } - this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE)); - this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE)); + this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS)); + this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); - boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE); - this.setUseBeanValidationFeature(useBeanValidationFeature); - if (useBeanValidationFeature) { - LOGGER.info("make sure your client supports Bean Validation 1.1"); - } supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen @@ -141,18 +144,16 @@ public class JavaCXFClientCodegen extends AbstractJavaCodegen implements CXFFeat } - public void setUseGzipFeature(boolean useGzipFeature) { - this.useGzipFeature = useGzipFeature; + public void setUseJaxbAnnotations(boolean useJaxbAnnotations) { + this.useJaxbAnnotations = useJaxbAnnotations; } - - public void setUseLoggingFeature(boolean useLoggingFeature) { - this.useLoggingFeature = useLoggingFeature; + public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests) { + this.useGzipFeatureForTests = useGzipFeatureForTests; } - - public void setUseBeanValidationFeature(boolean useBeanValidationFeature) { - this.useBeanValidationFeature = useBeanValidationFeature; + public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests) { + this.useLoggingFeatureForTests = useLoggingFeatureForTests; } - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index ced60722790..6404f74e3a0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -14,30 +14,48 @@ import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.SupportingFile; import io.swagger.codegen.languages.features.CXFServerFeatures; +import io.swagger.codegen.languages.features.GzipTestFeatures; +import io.swagger.codegen.languages.features.JaxbFeatures; +import io.swagger.codegen.languages.features.LoggingTestFeatures; import io.swagger.models.Operation; -public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen implements CXFServerFeatures +public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen + implements CXFServerFeatures, GzipTestFeatures, LoggingTestFeatures, JaxbFeatures { private static final Logger LOGGER = LoggerFactory.getLogger(JavaCXFServerCodegen.class); + protected boolean addConsumesProducesJson = true; + + protected boolean useJaxbAnnotations = true; + protected boolean useBeanValidation = false; protected boolean generateSpringApplication = false; + protected boolean useSpringAnnotationConfig = false; + protected boolean useSwaggerFeature = false; + protected boolean useSwaggerUI = false; + protected boolean useWadlFeature = false; protected boolean useMultipartFeature = false; - protected boolean useGzipFeature = false; - - protected boolean useLoggingFeature = false; - protected boolean useBeanValidationFeature = false; protected boolean generateSpringBootApplication= false; + protected boolean generateJbossDeploymentDescriptor = false; + + protected boolean useGzipFeature = false; + + protected boolean useGzipFeatureForTests = false; + + protected boolean useLoggingFeature = false; + + protected boolean useLoggingFeatureForTests = false; + public JavaCXFServerCodegen() { super(); @@ -64,18 +82,31 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf"; + cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application")); + cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config")); cliOptions.add(CliOption.newBoolean(USE_SWAGGER_FEATURE, "Use Swagger Feature")); + cliOptions.add(CliOption.newBoolean(USE_SWAGGER_UI, "Use Swagger UI")); + cliOptions.add(CliOption.newBoolean(USE_WADL_FEATURE, "Use WADL Feature")); cliOptions.add(CliOption.newBoolean(USE_MULTIPART_FEATURE, "Use Multipart Feature")); + cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE, "Use Gzip Feature")); + cliOptions.add(CliOption.newBoolean(USE_GZIP_FEATURE_FOR_TESTS, "Use Gzip Feature for tests")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION_FEATURE, "Use BeanValidation Feature")); cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE, "Use Logging Feature")); + cliOptions.add(CliOption.newBoolean(USE_LOGGING_FEATURE_FOR_TESTS, "Use Logging Feature for tests")); cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_BOOT_APPLICATION, "Generate Spring Boot application")); + cliOptions.add( + CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); + cliOptions + .add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface")); } @@ -85,19 +116,33 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme { super.processOpts(); + if (additionalProperties.containsKey(USE_JAXB_ANNOTATIONS)) { + boolean useJaxbAnnotationsProp = convertPropertyToBooleanAndWriteBack(USE_JAXB_ANNOTATIONS); + this.setUseJaxbAnnotations(useJaxbAnnotationsProp); + } + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); this.setUseBeanValidation(useBeanValidationProp); } + if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) { + this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON)); + } + if (additionalProperties.containsKey(GENERATE_SPRING_APPLICATION)) { this.setGenerateSpringApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_APPLICATION)); this.setUseSwaggerFeature(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_FEATURE)); + this.setUseSwaggerUI(convertPropertyToBooleanAndWriteBack(USE_SWAGGER_UI)); + this.setUseWadlFeature(convertPropertyToBooleanAndWriteBack(USE_WADL_FEATURE)); this.setUseMultipartFeature(convertPropertyToBooleanAndWriteBack(USE_MULTIPART_FEATURE)); this.setUseGzipFeature(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE)); + this.setUseGzipFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_GZIP_FEATURE_FOR_TESTS)); this.setUseLoggingFeature(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE)); + this.setUseLoggingFeatureForTests(convertPropertyToBooleanAndWriteBack(USE_LOGGING_FEATURE_FOR_TESTS)); + this.setUseSpringAnnotationConfig(convertPropertyToBooleanAndWriteBack(USE_SPRING_ANNOTATION_CONFIG)); boolean useBeanValidationFeature = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION_FEATURE); this.setUseBeanValidationFeature(useBeanValidationFeature); @@ -107,12 +152,20 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme this.setGenerateSpringBootApplication(convertPropertyToBooleanAndWriteBack(GENERATE_SPRING_BOOT_APPLICATION)); } - + if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) { + boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack( + GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); + } + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml")); + writeOptional(outputFolder, + new SupportingFile("server/swagger-codegen-ignore.mustache", "", ".swagger-codegen-ignore")); + if (this.generateSpringApplication) { writeOptional(outputFolder, new SupportingFile("server/readme.md", "", "readme.md")); @@ -124,14 +177,19 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme ("src/main/webapp/WEB-INF"), "context.xml")); // Jboss - writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache", - ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + if (generateJbossDeploymentDescriptor) { + writeOptional(outputFolder, new SupportingFile("server/jboss-web.xml.mustache", + ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + + } // Spring Boot if (this.generateSpringBootApplication) { writeOptional(outputFolder, new SupportingFile("server/SpringBootApplication.mustache", (testFolder + '/' + apiPackage).replace(".", "/"), "SpringBootApplication.java")); - + writeOptional(outputFolder, new SupportingFile("server/application.properties.mustache", + (testResourcesFolder + '/'), "application.properties")); + } } @@ -174,6 +232,9 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme this.generateSpringApplication = generateSpringApplication; } + public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig) { + this.useSpringAnnotationConfig = useSpringAnnotationConfig; + } public void setUseSwaggerFeature(boolean useSwaggerFeature) { this.useSwaggerFeature = useSwaggerFeature; @@ -204,7 +265,32 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen impleme this.useBeanValidationFeature = useBeanValidationFeature; } - public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) { + public void setGenerateSpringBootApplication(boolean generateSpringBootApplication) { this.generateSpringBootApplication = generateSpringBootApplication; } + + public void setUseJaxbAnnotations(boolean useJaxbAnnotations) { + this.useJaxbAnnotations = useJaxbAnnotations; + } + + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { + this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; + } + + public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests) { + this.useGzipFeatureForTests = useGzipFeatureForTests; + } + + public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests) { + this.useLoggingFeatureForTests = useLoggingFeatureForTests; + } + + public void setUseSwaggerUI(boolean useSwaggerUI) { + this.useSwaggerUI = useSwaggerUI; + } + + public void setAddConsumesProducesJson(boolean addConsumesProducesJson) { + this.addConsumesProducesJson = addConsumesProducesJson; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index d2a462c1e2d..c1bd8a23cd5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.JbossFeature; import io.swagger.models.Operation; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; @@ -8,7 +9,9 @@ import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.*; -public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { +public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature { + + protected boolean generateJbossDeploymentDescriptor = true; public JavaResteasyServerCodegen() { @@ -31,6 +34,9 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { dateLibrary = "legacy";// TODO: change to joda embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy"; + + cliOptions.add( + CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); } @Override @@ -47,6 +53,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)) { + boolean generateJbossDeploymentDescriptorProp = convertPropertyToBooleanAndWriteBack( + GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); + } + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); @@ -61,8 +73,12 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { (sourceFolder + '/' + apiPackage).replace(".", "/"), "NotFoundException.java")); writeOptional(outputFolder, new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); - writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", + + if (generateJbossDeploymentDescriptor) { + writeOptional(outputFolder, new SupportingFile("jboss-web.mustache", ("src/main/webapp/WEB-INF"), "jboss-web.xml")); + } + writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", @@ -198,4 +214,8 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen { return objs; } + + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { + this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFFeatures.java index 64fa569c83f..638f0ebf5c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFFeatures.java @@ -4,6 +4,8 @@ package io.swagger.codegen.languages.features; * Features supported by CXF 3 (client + server) * */ -public interface CXFFeatures extends LoggingFeatures, GzipFeatures, BeanValidationFeatures, BeanValidationExtendedFeatures { +public interface CXFFeatures extends LoggingFeatures, GzipFeatures, BeanValidationFeatures { + + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java index 5c12aaedef6..eaa012b987a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java @@ -1,17 +1,24 @@ -package io.swagger.codegen.languages.features; - -/** - * Features supported by CXF 3 server - * - */ -public interface CXFServerFeatures extends CXFFeatures, SwaggerFeatures, SpringFeatures { - - public static final String USE_WADL_FEATURE = "useWadlFeature"; - - public static final String USE_MULTIPART_FEATURE = "useMultipartFeature"; - - public void setUseWadlFeature(boolean useWadlFeature); - - public void setUseMultipartFeature(boolean useMultipartFeature); - -} +package io.swagger.codegen.languages.features; + +/** + * Features supported by CXF 3 server + * + */ +public interface CXFServerFeatures + extends CXFFeatures, SwaggerFeatures, SpringFeatures, JbossFeature, BeanValidationExtendedFeatures, + SwaggerUIFeatures +{ + + public static final String USE_WADL_FEATURE = "useWadlFeature"; + + public static final String USE_MULTIPART_FEATURE = "useMultipartFeature"; + + public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson"; + + public void setUseWadlFeature(boolean useWadlFeature); + + public void setUseMultipartFeature(boolean useMultipartFeature); + + public void setAddConsumesProducesJson(boolean addConsumesProducesJson); + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java index b117708232c..4cb9955187e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipFeatures.java @@ -3,7 +3,7 @@ package io.swagger.codegen.languages.features; public interface GzipFeatures { public static final String USE_GZIP_FEATURE = "useGzipFeature"; - + public void setUseGzipFeature(boolean useGzipFeature); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipTestFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipTestFeatures.java new file mode 100644 index 00000000000..871179ae991 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/GzipTestFeatures.java @@ -0,0 +1,9 @@ +package io.swagger.codegen.languages.features; + +public interface GzipTestFeatures { + + public static final String USE_GZIP_FEATURE_FOR_TESTS = "useGzipFeatureForTests"; + + public void setUseGzipFeatureForTests(boolean useGzipFeatureForTests); + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JaxbFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JaxbFeatures.java new file mode 100644 index 00000000000..9693d6dcd07 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JaxbFeatures.java @@ -0,0 +1,7 @@ +package io.swagger.codegen.languages.features; + +public interface JaxbFeatures { + public static final String USE_JAXB_ANNOTATIONS = "useJaxbAnnotations"; + + public void setUseJaxbAnnotations(boolean useJaxbAnnotations); +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java new file mode 100644 index 00000000000..9cbbd34be81 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/JbossFeature.java @@ -0,0 +1,9 @@ +package io.swagger.codegen.languages.features; + +public interface JbossFeature { + + public static final String GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR = "generateJbossDeploymentDescriptor"; + + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor); + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingTestFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingTestFeatures.java new file mode 100644 index 00000000000..8a210f8a87c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/LoggingTestFeatures.java @@ -0,0 +1,8 @@ +package io.swagger.codegen.languages.features; + +public interface LoggingTestFeatures { + public static final String USE_LOGGING_FEATURE_FOR_TESTS = "useLoggingFeatureForTests"; + + public void setUseLoggingFeatureForTests(boolean useLoggingFeatureForTests); + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java index e7cb6c18228..0a3fad4202a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SpringFeatures.java @@ -6,9 +6,13 @@ public interface SpringFeatures extends BeanValidationFeatures { public static final String GENERATE_SPRING_BOOT_APPLICATION = "generateSpringBootApplication"; + public static final String USE_SPRING_ANNOTATION_CONFIG = "useSpringAnnotationConfig"; + public void setGenerateSpringApplication(boolean useGenerateSpringApplication); public void setGenerateSpringBootApplication(boolean generateSpringBootApplication); + public void setUseSpringAnnotationConfig(boolean useSpringAnnotationConfig); + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SwaggerUIFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SwaggerUIFeatures.java new file mode 100644 index 00000000000..1ed4a586287 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/SwaggerUIFeatures.java @@ -0,0 +1,9 @@ +package io.swagger.codegen.languages.features; + +public interface SwaggerUIFeatures extends CXFFeatures { + + public static final String USE_SWAGGER_UI = "useSwaggerUI"; + + public void setUseSwaggerUI(boolean useSwaggerUI); + +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index f1efbe87c63..7fbcc9cea4d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -1,36 +1,44 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} - -@Path("/") -@Api(value = "/", description = "{{description}}") -public interface {{classname}} { -{{#operations}} -{{#operation}} - - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); -{{/operation}} -} -{{/operations}} - +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} + +@Path("/") +@Api(value = "/", description = "{{description}}") +{{#addConsumesProducesJson}} +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +{{/addConsumesProducesJson}} +public interface {{classname}} { +{{#operations}} +{{#operation}} + + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} +{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) +{{/hasConsumes}} +{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) +{{/hasProduces}} + @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index c0199a9b5ca..ee5d8269955 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -16,13 +16,19 @@ import org.apache.cxf.jaxrs.model.wadl.DocTarget; import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; +{{#useSpringAnnotationConfig}} +import org.springframework.stereotype.Service; +{{/useSpringAnnotationConfig}} +{{#useSpringAnnotationConfig}} +@Service("{{classname}}") +{{/useSpringAnnotationConfig}} {{#description}} {{/description}} public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... {{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index 43e9222d45e..34308df4314 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -6,6 +6,7 @@ package {{package}}; {{/imports}} import org.junit.Test; import org.junit.Before; +import static org.junit.Assert.*; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.client.JAXRSClientFactory; @@ -65,7 +66,7 @@ public class {{classname}}Test { providers.add(provider); {{#generateSpringBootApplication}} - api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services/services", {{classname}}.class, providers); + api = JAXRSClientFactory.create("http://localhost:" + serverPort + "/services", {{classname}}.class, providers); {{/generateSpringBootApplication}} {{^generateSpringBootApplication}} api = JAXRSClientFactory.create("{{basePath}}", {{classname}}.class, providers); @@ -73,7 +74,7 @@ public class {{classname}}Test { org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); ClientConfiguration config = WebClient.getConfig(client); -{{#useGzipFeature}} +{{#useGzipFeatureForTests}} // Example for using Gzipping GZIPOutInterceptor gzipOutInterceptor = new GZIPOutInterceptor(); // use Gzipping for first request sent to server @@ -81,11 +82,11 @@ public class {{classname}}Test { config.getOutInterceptors().add(gzipOutInterceptor); config.getInInterceptors().add(new GZIPInInterceptor()); -{{/useGzipFeature}} -{{#useLoggingFeature}} +{{/useGzipFeatureForTests}} +{{#useLoggingFeatureForTests}} LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor(); config.getOutInterceptors().add(loggingOutInterceptor); -{{/useLoggingFeature}} +{{/useLoggingFeatureForTests}} } {{#operations}}{{#operation}} @@ -100,11 +101,13 @@ public class {{classname}}Test { @Test public void {{operationId}}Test() { {{#allParams}} - {{{dataType}}} {{paramName}} = null; + {{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}}{{#isFile}}org.apache.cxf.jaxrs.ext.multipart.Attachment {{paramName}} = null;{{/isFile}} {{/allParams}} - // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - + //{{^vendorExtensions.x-java-is-response-void}}{{{returnType}}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{^vendorExtensions.x-java-is-response-void}}//assertNotNull(response);{{/vendorExtensions.x-java-is-response-void}} // TODO: test validations + + } {{/operation}}{{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..cca08f4b2c4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}}/* @Min({{minimum}}) */{{/minimum}}{{#maximum}}/* @Max({{maximum}}) */{{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache new file mode 100644 index 00000000000..85de81431b6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumOuterClass.mustache @@ -0,0 +1,43 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache index c129a925e94..f4988929e52 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParams.mustache @@ -1,2 +1 @@ -{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, - @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@Multipart(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @Multipart(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache new file mode 100644 index 00000000000..e8c0e77c156 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/formParamsImpl.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParamsImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParamsImpl.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/headerParamsImpl.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache index aa3501d796e..0030cf7dd0c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/model.mustache @@ -9,7 +9,7 @@ import javax.validation.constraints.*; {{#models}} {{#model}} {{#isEnum}} -{{>enumClass}} +{{>enumOuterClass}} {{/isEnum}} {{^isEnum}} {{>pojo}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParamsImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParamsImpl.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pathParamsImpl.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 9f00536089c..b959ce17c15 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -7,12 +7,14 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; +{{#useJaxbAnnotations}} @XmlAccessorType(XmlAccessType.FIELD) {{#hasVars}} @XmlType(name = "{{classname}}", propOrder = { {{#vars}}"{{name}}"{{^-last}}, {{/-last}}{{/vars}} }){{/hasVars}} {{^hasVars}}@XmlType(name = "{{classname}}"){{/hasVars}} {{^parent}}@XmlRootElement(name="{{classname}}"){{/parent}} +{{/useJaxbAnnotations}} {{#description}} @ApiModel(description="{{{description}}}") {{/description}} @@ -22,8 +24,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} {{>enumClass}}{{/items}}{{/items.isEnum}} - +{{#useJaxbAnnotations}} @XmlElement(name="{{baseName}}") +{{/useJaxbAnnotations}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache index 6b16d47e340..ef3bf519c43 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/ApplicationContext.xml.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/ApplicationContext.xml.mustache index 2cb4720da8c..b4cdc5b6cfd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/ApplicationContext.xml.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/ApplicationContext.xml.mustache @@ -11,8 +11,6 @@ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> - - @@ -23,18 +21,27 @@ {{/useMultipartFeature}} +{{#useSpringAnnotationConfig}} + + +{{/useSpringAnnotationConfig}} +{{^useSpringAnnotationConfig}} {{#apiInfo}} {{#apis}} {{/apis}} {{/apiInfo}} +{{/useSpringAnnotationConfig}} {{#useSwaggerFeature}} {{! http://cxf.apache.org/docs/swagger2feature.html }} - +{{#useSwaggerUI}} + +{{/useSwaggerUI}} + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + +
    + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + 3.1.6 + UTF-8 + + diff --git a/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..4ff1aa826dc --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface PetApi { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", tags={ }) + public void addPet(Pet body); + + @DELETE + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", tags={ }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ }) + public List findPetsByStatus(@QueryParam("status")List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ }) + public List findPetsByTags(@QueryParam("tags")List tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ }) + public Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", tags={ }) + public void updatePet(Pet body); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ }) + public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, + @Multipart(value = "file" , required = false) Attachment fileDetail); +} + diff --git a/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..dca146745e8 --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,47 @@ +package io.swagger.api; + +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface StoreApi { + + @DELETE + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", tags={ }) + public void deleteOrder(@PathParam("orderId") String orderId); + + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ }) + public Map getInventory(); + + @GET + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ }) + public Order getOrderById(@PathParam("orderId") Long orderId); + + @POST + @Path("/store/order") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ }) + public Order placeOrder(Order body); +} + diff --git a/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..e3e77a12361 --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,71 @@ +package io.swagger.api; + +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface UserApi { + + @POST + @Path("/user") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", tags={ }) + public void createUser(User body); + + @POST + @Path("/user/createWithArray") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ }) + public void createUsersWithArrayInput(List body); + + @POST + @Path("/user/createWithList") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ }) + public void createUsersWithListInput(List body); + + @DELETE + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", tags={ }) + public void deleteUser(@PathParam("username") String username); + + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ }) + public User getUserByName(@PathParam("username") String username); + + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ }) + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + + @GET + @Path("/user/logout") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", tags={ }) + public void logoutUser(); + + @PUT + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", tags={ }) + public void updateUser(@PathParam("username") String username, User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java similarity index 82% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java index ecd7630f6a7..591a6e22a69 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Category.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java @@ -2,6 +2,7 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -10,33 +11,28 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Category", propOrder = - { "id", "name" -}) - -@XmlRootElement(name="Category") +@ApiModel(description="A category for a pet") public class Category { - - @XmlElement(name="id") + @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="name") + @ApiModelProperty(example = "null", value = "") private String name = null; - /** - **/ - + /** + * Get id + * @return id + **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - **/ - + /** + * Get name + * @return name + **/ public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java similarity index 79% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java index dc8a57cf13a..f3c6f56cfc4 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -2,6 +2,7 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -10,45 +11,40 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "ModelApiResponse", propOrder = - { "code", "type", "message" -}) - -@XmlRootElement(name="ModelApiResponse") +@ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { - - @XmlElement(name="code") + @ApiModelProperty(example = "null", value = "") private Integer code = null; - - @XmlElement(name="type") + @ApiModelProperty(example = "null", value = "") private String type = null; - - @XmlElement(name="message") + @ApiModelProperty(example = "null", value = "") private String message = null; - /** - **/ - + /** + * Get code + * @return code + **/ public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } - /** - **/ - + /** + * Get type + * @return type + **/ public String getType() { return type; } public void setType(String type) { this.type = type; } - /** - **/ - + /** + * Get message + * @return message + **/ public String getMessage() { return message; } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java similarity index 81% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java index ec2140e1b4d..af6f5e0e38e 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Order.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java @@ -2,6 +2,7 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -10,25 +11,16 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Order", propOrder = - { "id", "petId", "quantity", "shipDate", "status", "complete" -}) - -@XmlRootElement(name="Order") +@ApiModel(description="An order for a pets from the pet store") public class Order { - - @XmlElement(name="id") + @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="petId") + @ApiModelProperty(example = "null", value = "") private Long petId = null; - - @XmlElement(name="quantity") + @ApiModelProperty(example = "null", value = "") private Integer quantity = null; - - @XmlElement(name="shipDate") + @ApiModelProperty(example = "null", value = "") private javax.xml.datatype.XMLGregorianCalendar shipDate = null; @XmlType(name="StatusEnum") @@ -63,62 +55,65 @@ public enum StatusEnum { } } - - @XmlElement(name="status") + @ApiModelProperty(example = "null", value = "Order Status") private StatusEnum status = null; - - @XmlElement(name="complete") + @ApiModelProperty(example = "null", value = "") private Boolean complete = false; - /** - **/ - + /** + * Get id + * @return id + **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - **/ - + /** + * Get petId + * @return petId + **/ public Long getPetId() { return petId; } public void setPetId(Long petId) { this.petId = petId; } - /** - **/ - + /** + * Get quantity + * @return quantity + **/ public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } - /** - **/ - + /** + * Get shipDate + * @return shipDate + **/ public javax.xml.datatype.XMLGregorianCalendar getShipDate() { return shipDate; } public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { this.shipDate = shipDate; } - /** + /** * Order Status - **/ - + * @return status + **/ public StatusEnum getStatus() { return status; } public void setStatus(StatusEnum status) { this.status = status; } - /** - **/ - + /** + * Get complete + * @return complete + **/ public Boolean getComplete() { return complete; } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java similarity index 81% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java index 5a636e92c33..0cfc0a30ee0 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java @@ -6,6 +6,7 @@ import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -14,28 +15,18 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Pet", propOrder = - { "id", "category", "name", "photoUrls", "tags", "status" -}) - -@XmlRootElement(name="Pet") +@ApiModel(description="A pet for sale in the pet store") public class Pet { - - @XmlElement(name="id") + @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="category") + @ApiModelProperty(example = "null", value = "") private Category category = null; - - @XmlElement(name="name") + @ApiModelProperty(example = "doggie", required = true, value = "") private String name = null; - - @XmlElement(name="photoUrls") + @ApiModelProperty(example = "null", required = true, value = "") private List photoUrls = new ArrayList(); - - @XmlElement(name="tags") + @ApiModelProperty(example = "null", value = "") private List tags = new ArrayList(); @XmlType(name="StatusEnum") @@ -70,59 +61,63 @@ public enum StatusEnum { } } - - @XmlElement(name="status") + @ApiModelProperty(example = "null", value = "pet status in the store") private StatusEnum status = null; - /** - **/ - + /** + * Get id + * @return id + **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - **/ - + /** + * Get category + * @return category + **/ public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } - /** - **/ - + /** + * Get name + * @return name + **/ public String getName() { return name; } public void setName(String name) { this.name = name; } - /** - **/ - + /** + * Get photoUrls + * @return photoUrls + **/ public List getPhotoUrls() { return photoUrls; } public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - /** - **/ - + /** + * Get tags + * @return tags + **/ public List getTags() { return tags; } public void setTags(List tags) { this.tags = tags; } - /** + /** * pet status in the store - **/ - + * @return status + **/ public StatusEnum getStatus() { return status; } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java similarity index 82% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java index 848da3841f0..4eb99ad2fc1 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java @@ -2,6 +2,7 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -10,33 +11,28 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "Tag", propOrder = - { "id", "name" -}) - -@XmlRootElement(name="Tag") +@ApiModel(description="A tag for a pet") public class Tag { - - @XmlElement(name="id") + @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="name") + @ApiModelProperty(example = "null", value = "") private String name = null; - /** - **/ - + /** + * Get id + * @return id + **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - **/ - + /** + * Get name + * @return name + **/ public String getName() { return name; } diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java similarity index 75% rename from samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java rename to samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java index e08637a5777..005d9aa8c74 100644 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/model/User.java +++ b/samples/client/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java @@ -2,6 +2,7 @@ package io.swagger.model; import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlAccessType; @@ -10,106 +11,100 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@XmlAccessorType(XmlAccessType.FIELD) - @XmlType(name = "User", propOrder = - { "id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus" -}) - -@XmlRootElement(name="User") +@ApiModel(description="A User who is purchasing from the pet store") public class User { - - @XmlElement(name="id") + @ApiModelProperty(example = "null", value = "") private Long id = null; - - @XmlElement(name="username") + @ApiModelProperty(example = "null", value = "") private String username = null; - - @XmlElement(name="firstName") + @ApiModelProperty(example = "null", value = "") private String firstName = null; - - @XmlElement(name="lastName") + @ApiModelProperty(example = "null", value = "") private String lastName = null; - - @XmlElement(name="email") + @ApiModelProperty(example = "null", value = "") private String email = null; - - @XmlElement(name="password") + @ApiModelProperty(example = "null", value = "") private String password = null; - - @XmlElement(name="phone") + @ApiModelProperty(example = "null", value = "") private String phone = null; - - @XmlElement(name="userStatus") + @ApiModelProperty(example = "null", value = "User Status") private Integer userStatus = null; - /** - **/ - + /** + * Get id + * @return id + **/ public Long getId() { return id; } public void setId(Long id) { this.id = id; } - /** - **/ - + /** + * Get username + * @return username + **/ public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } - /** - **/ - + /** + * Get firstName + * @return firstName + **/ public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } - /** - **/ - + /** + * Get lastName + * @return lastName + **/ public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } - /** - **/ - + /** + * Get email + * @return email + **/ public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } - /** - **/ - + /** + * Get password + * @return password + **/ public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } - /** - **/ - + /** + * Get phone + * @return phone + **/ public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } - /** + /** * User Status - **/ - + * @return userStatus + **/ public Integer getUserStatus() { return userStatus; } diff --git a/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..9d4a9de9901 --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,205 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for PetApi + */ +public class PetApiTest { + + + private PetApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", PetApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + // response = api.addPet(body); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + // response = api.deletePet(petId, apiKey); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + //List response = api.findPetsByStatus(status); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + //List response = api.findPetsByTags(tags); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + //Pet response = api.getPetById(petId); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + // response = api.updatePet(body); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + // response = api.updatePetWithForm(petId, name, status); + //assertNotNull(response); + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + //ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + //assertNotNull(response); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..81053a82b29 --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,133 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + + private StoreApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", StoreApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + String orderId = null; + // response = api.deleteOrder(orderId); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + //Map response = api.getInventory(); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + //Order response = api.getOrderById(orderId); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + //Order response = api.placeOrder(body); + //assertNotNull(response); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..126c7018935 --- /dev/null +++ b/samples/client/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,199 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import io.swagger.model.User; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for UserApi + */ +public class UserApiTest { + + + private UserApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", UserApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + // response = api.createUser(body); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + // response = api.createUsersWithArrayInput(body); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + // response = api.createUsersWithListInput(body); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + // response = api.deleteUser(username); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + //User response = api.getUserByName(username); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + //String response = api.loginUser(username, password); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + // response = api.logoutUser(); + //assertNotNull(response); + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + // response = api.updateUser(username, body); + //assertNotNull(response); + // TODO: test validations + } + +} diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java deleted file mode 100644 index 9e459c248dd..00000000000 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/PetApi.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.Pet; -import java.io.File; -import io.swagger.model.ModelApiResponse; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -@Path("/v2") -public interface PetApi { - @POST - @Path("/pet") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - Response addPet(Pet body); - @DELETE - @Path("/pet/{petId}") - - @Produces({ "application/xml", "application/json" }) - Response deletePet(@PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey); - @GET - @Path("/pet/findByStatus") - - @Produces({ "application/xml", "application/json" }) - Response findPetsByStatus(@QueryParam("status") List status); - @GET - @Path("/pet/findByTags") - - @Produces({ "application/xml", "application/json" }) - Response findPetsByTags(@QueryParam("tags") List tags); - @GET - @Path("/pet/{petId}") - - @Produces({ "application/xml", "application/json" }) - Response getPetById(@PathParam("petId") Long petId); - @PUT - @Path("/pet") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - Response updatePet(Pet body); - @POST - @Path("/pet/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/xml", "application/json" }) - Response updatePetWithForm(@PathParam("petId") Long petId,@Multipart(value = "name", required = false) String name,@Multipart(value = "status", required = false) String status); - @POST - @Path("/pet/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json" }) - Response uploadFile(@PathParam("petId") Long petId,@Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, - @Multipart(value = "file" , required = false) Attachment fileDetail); -} - diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java deleted file mode 100644 index 2bdd151ec3f..00000000000 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/StoreApi.java +++ /dev/null @@ -1,38 +0,0 @@ -package io.swagger.api; - -import java.util.Map; -import io.swagger.model.Order; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -@Path("/v2") -public interface StoreApi { - @DELETE - @Path("/store/order/{orderId}") - - @Produces({ "application/xml", "application/json" }) - Response deleteOrder(@PathParam("orderId") String orderId); - @GET - @Path("/store/inventory") - - @Produces({ "application/json" }) - Response getInventory(); - @GET - @Path("/store/order/{orderId}") - - @Produces({ "application/xml", "application/json" }) - Response getOrderById(@PathParam("orderId") Long orderId); - @POST - @Path("/store/order") - - @Produces({ "application/xml", "application/json" }) - Response placeOrder(Order body); -} - diff --git a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java deleted file mode 100644 index f93523bf947..00000000000 --- a/samples/server/petstore/jaxrs-cxf/gen/java/io/swagger/api/UserApi.java +++ /dev/null @@ -1,58 +0,0 @@ -package io.swagger.api; - -import io.swagger.model.User; -import java.util.List; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import org.apache.cxf.jaxrs.ext.multipart.*; - -@Path("/v2") -public interface UserApi { - @POST - @Path("/user") - - @Produces({ "application/xml", "application/json" }) - Response createUser(User body); - @POST - @Path("/user/createWithArray") - - @Produces({ "application/xml", "application/json" }) - Response createUsersWithArrayInput(List body); - @POST - @Path("/user/createWithList") - - @Produces({ "application/xml", "application/json" }) - Response createUsersWithListInput(List body); - @DELETE - @Path("/user/{username}") - - @Produces({ "application/xml", "application/json" }) - Response deleteUser(@PathParam("username") String username); - @GET - @Path("/user/{username}") - - @Produces({ "application/xml", "application/json" }) - Response getUserByName(@PathParam("username") String username); - @GET - @Path("/user/login") - - @Produces({ "application/xml", "application/json" }) - Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password); - @GET - @Path("/user/logout") - - @Produces({ "application/xml", "application/json" }) - Response logoutUser(); - @PUT - @Path("/user/{username}") - - @Produces({ "application/xml", "application/json" }) - Response updateUser(@PathParam("username") String username,User body); -} - diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml index 24ae04f9d19..cdf3a68ed8f 100644 --- a/samples/server/petstore/jaxrs-cxf/pom.xml +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -82,7 +82,7 @@ maven-war-plugin 2.1.1 - true + false @@ -165,13 +165,13 @@ 1.7 ${java.version} ${java.version} - 1.5.9 + 1.5.10 9.2.9.v20150224 2.22.2 4.12 1.1.7 2.5 - 3.1.7 + 3.1.8 UTF-8 diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..608b51f96d8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,77 @@ +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface PetApi { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + public void addPet(Pet body); + + @DELETE + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + public Pet findPetsByStatus(@QueryParam("status")List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + public Pet findPetsByTags(@QueryParam("tags")List tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + public Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + public void updatePet(Pet body); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ "pet" }) + public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..87a583b8712 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,48 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface StoreApi { + + @DELETE + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + public void deleteOrder(@PathParam("orderId") String orderId); + + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + public Integer getInventory(); + + @GET + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + public Order getOrderById(@PathParam("orderId") Long orderId); + + @POST + @Path("/store/order") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + public Order placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..528af584f46 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,72 @@ +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface UserApi { + + @POST + @Path("/user") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", tags={ "user", }) + public void createUser(User body); + + @POST + @Path("/user/createWithArray") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithArrayInput(List body); + + @POST + @Path("/user/createWithList") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithListInput(List body); + + @DELETE + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", tags={ "user", }) + public void deleteUser(@PathParam("username") String username); + + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ "user", }) + public User getUserByName(@PathParam("username") String username); + + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ "user", }) + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + + @GET + @Path("/user/logout") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + public void logoutUser(); + + @PUT + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", tags={ "user" }) + public void updateUser(@PathParam("username") String username, User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..591a6e22a69 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A category for a pet") +public class Category { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + 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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..f3c6f56cfc4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,78 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Describes the result of uploading an image resource") +public class ModelApiResponse { + + @ApiModelProperty(example = "null", value = "") + private Integer code = null; + @ApiModelProperty(example = "null", value = "") + private String type = null; + @ApiModelProperty(example = "null", value = "") + private String message = null; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..af6f5e0e38e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,150 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="An order for a pets from the pet store") +public class Order { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Long petId = null; + @ApiModelProperty(example = "null", value = "") + private Integer quantity = null; + @ApiModelProperty(example = "null", value = "") + private javax.xml.datatype.XMLGregorianCalendar shipDate = null; + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "Order Status") + private StatusEnum status = null; + @ApiModelProperty(example = "null", value = "") + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + /** + * Get shipDate + * @return shipDate + **/ + public javax.xml.datatype.XMLGregorianCalendar getShipDate() { + return shipDate; + } + public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + } + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + /** + * Get complete + * @return complete + **/ + 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(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..0cfc0a30ee0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,154 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A pet for sale in the pet store") +public class Pet { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Category category = null; + @ApiModelProperty(example = "doggie", required = true, value = "") + private String name = null; + @ApiModelProperty(example = "null", required = true, value = "") + private List photoUrls = new ArrayList(); + @ApiModelProperty(example = "null", value = "") + private List tags = new ArrayList(); + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "pet status in the store") + private StatusEnum status = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + /** + * Get photoUrls + * @return photoUrls + **/ + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + /** + * pet status in the store + * @return status + **/ + 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(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..4eb99ad2fc1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A tag for a pet") +public class Tag { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + 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(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..005d9aa8c74 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,143 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A User who is purchasing from the pet store") +public class User { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String username = null; + @ApiModelProperty(example = "null", value = "") + private String firstName = null; + @ApiModelProperty(example = "null", value = "") + private String lastName = null; + @ApiModelProperty(example = "null", value = "") + private String email = null; + @ApiModelProperty(example = "null", value = "") + private String password = null; + @ApiModelProperty(example = "null", value = "") + private String phone = null; + @ApiModelProperty(example = "null", value = "User Status") + private Integer userStatus = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + /** + * User Status + * @return userStatus + **/ + 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(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..9c952820070 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,71 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class PetApiServiceImpl implements PetApi { + public void addPet(Pet body) { + // TODO: Implement... + + + } + + public void deletePet(Long petId, String apiKey) { + // TODO: Implement... + + + } + + public Pet findPetsByStatus(List status) { + // TODO: Implement... + + return null; + } + + public Pet findPetsByTags(List tags) { + // TODO: Implement... + + return null; + } + + public Pet getPetById(Long petId) { + // TODO: Implement... + + return null; + } + + public void updatePet(Pet body) { + // TODO: Implement... + + + } + + public void updatePetWithForm(Long petId, String name, String status) { + // TODO: Implement... + + + } + + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..cbcc2de9e2a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,46 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class StoreApiServiceImpl implements StoreApi { + public void deleteOrder(String orderId) { + // TODO: Implement... + + + } + + public Integer getInventory() { + // TODO: Implement... + + return null; + } + + public Order getOrderById(Long orderId) { + // TODO: Implement... + + return null; + } + + public Order placeOrder(Order body) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..8fac5414a23 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,70 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.User; +import java.util.List; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class UserApiServiceImpl implements UserApi { + public void createUser(User body) { + // TODO: Implement... + + + } + + public void createUsersWithArrayInput(List body) { + // TODO: Implement... + + + } + + public void createUsersWithListInput(List body) { + // TODO: Implement... + + + } + + public void deleteUser(String username) { + // TODO: Implement... + + + } + + public User getUserByName(String username) { + // TODO: Implement... + + return null; + } + + public String loginUser(String username, String password) { + // TODO: Implement... + + return null; + } + + public void logoutUser() { + // TODO: Implement... + + + } + + public void updateUser(String username, User body) { + // TODO: Implement... + + + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..44cf564dec1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,221 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import io.swagger.model.Pet; +import io.swagger.model.ModelApiResponse; +import java.io.File; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for PetApi + */ +public class PetApiTest { + + + private PetApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", PetApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + //api.addPet(body); + + // TODO: test validations + + + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + //api.deletePet(petId, apiKey); + + // TODO: test validations + + + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + //Pet response = api.findPetsByStatus(status); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + //Pet response = api.findPetsByTags(tags); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + //Pet response = api.getPetById(petId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + //api.updatePet(body); + + // TODO: test validations + + + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + //api.updatePetWithForm(petId, name, status); + + // TODO: test validations + + + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + org.apache.cxf.jaxrs.ext.multipart.Attachment file = null; + //ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..e54e33f0fbc --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,142 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + + private StoreApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", StoreApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + String orderId = null; + //api.deleteOrder(orderId); + + // TODO: test validations + + + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + //Integer response = api.getInventory(); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + //Order response = api.getOrderById(orderId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + //Order response = api.placeOrder(body); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..2285f3c70cf --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,216 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +package io.swagger.api; + +import io.swagger.model.User; +import java.util.List; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for UserApi + */ +public class UserApiTest { + + + private UserApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", UserApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + //api.createUser(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + //api.createUsersWithArrayInput(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + //api.createUsersWithListInput(body); + + // TODO: test validations + + + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + //api.deleteUser(username); + + // TODO: test validations + + + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + //User response = api.getUserByName(username); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + //String response = api.loginUser(username, password); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + //api.logoutUser(); + + // TODO: test validations + + + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + //api.updateUser(username, body); + + // TODO: test validations + + + } + +} From df15799839b0b548fd2a75341d075f43e0e98e4b Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Sat, 19 Nov 2016 09:31:31 +0100 Subject: [PATCH 083/269] [Flask] Add generated tests (#4209) --- .../io/swagger/codegen/DefaultCodegen.java | 57 ++++----- .../languages/FlaskConnexionCodegen.java | 104 ++++++++++++++- .../resources/flaskConnexion/README.mustache | 4 +- .../flaskConnexion/__init__test.mustache | 14 +++ .../flaskConnexion/controller_test.mustache | 49 ++++++++ .../petstore/flaskConnexion-python2/README.md | 2 +- .../controllers/pet_controller.py | 2 +- .../flaskConnexion-python2/test/__init__.py | 14 +++ .../test/test_pet_controller.py | 118 ++++++++++++++++++ .../test/test_store_controller.py | 60 +++++++++ .../test/test_user_controller.py | 112 +++++++++++++++++ .../server/petstore/flaskConnexion/README.md | 2 +- .../controllers/pet_controller.py | 2 +- .../petstore/flaskConnexion/test/__init__.py | 14 +++ .../test/test_pet_controller.py | 118 ++++++++++++++++++ .../test/test_store_controller.py | 60 +++++++++ .../test/test_user_controller.py | 112 +++++++++++++++++ 17 files changed, 806 insertions(+), 38 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache create mode 100644 samples/server/petstore/flaskConnexion-python2/test/__init__.py create mode 100644 samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py create mode 100644 samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py create mode 100644 samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py create mode 100644 samples/server/petstore/flaskConnexion/test/__init__.py create mode 100644 samples/server/petstore/flaskConnexion/test/test_pet_controller.py create mode 100644 samples/server/petstore/flaskConnexion/test/test_store_controller.py create mode 100644 samples/server/petstore/flaskConnexion/test/test_user_controller.py diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 5ccc9b24945..8a9b8accd38 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2392,6 +2392,31 @@ public class DefaultCodegen { p.paramName = toParamName(bp.getName()); } + // Issue #2561 (neilotoole) : Set the isParam flags. + // This code has been moved to here from #fromOperation + // because these values should be set before calling #postProcessParameter. + // See: https://github.com/swagger-api/swagger-codegen/issues/2561 + if (param instanceof QueryParameter) { + p.isQueryParam = true; + } else if (param instanceof PathParameter) { + p.required = true; + p.isPathParam = true; + } else if (param instanceof HeaderParameter) { + p.isHeaderParam = true; + } else if (param instanceof CookieParameter) { + p.isCookieParam = true; + } else if (param instanceof BodyParameter) { + p.isBodyParam = true; + p.isBinary = isDataTypeBinary(p.dataType); + } else if (param instanceof FormParameter) { + if ("file".equalsIgnoreCase(((FormParameter) param).getType()) || "file".equals(p.baseType)) { + p.isFile = true; + } else { + p.notFile = true; + } + p.isFormParam = true; + } + // set the example value // if not specified in x-example, generate a default value if (p.vendorExtensions.containsKey("x-example")) { @@ -2416,10 +2441,7 @@ public class DefaultCodegen { p.example = "2013-10-20"; } else if (Boolean.TRUE.equals(p.isDateTime)) { p.example = "2013-10-20T19:20:30+01:00"; - } else if (param instanceof FormParameter && - ("file".equalsIgnoreCase(((FormParameter) param).getType()) || - "file".equals(p.baseType))) { - p.isFile = true; + } else if (Boolean.TRUE.equals(p.isFile)) { p.example = "/path/to/file.txt"; } @@ -2427,33 +2449,6 @@ public class DefaultCodegen { // should be overridden by lang codegen setParameterExampleValue(p); - // Issue #2561 (neilotoole) : Set the isParam flags. - // This code has been moved to here from #fromOperation - // because these values should be set before calling #postProcessParameter. - // See: https://github.com/swagger-api/swagger-codegen/issues/2561 - if (param instanceof QueryParameter) { - p.isQueryParam = true; - } else if (param instanceof PathParameter) { - p.required = true; - p.isPathParam = true; - } else if (param instanceof HeaderParameter) { - p.isHeaderParam = true; - } else if (param instanceof CookieParameter) { - p.isCookieParam = true; - } else if (param instanceof BodyParameter) { - p.isBodyParam = true; - p.isBinary = isDataTypeBinary(p.dataType); - } else if (param instanceof FormParameter) { - if ("file".equalsIgnoreCase(((FormParameter) param).getType())) { - p.isFile = true; - } else if("file".equals(p.baseType)){ - p.isFile = true; - } else { - p.notFile = true; - } - p.isFormParam = true; - } - postProcessParameter(p); return p; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 0a9f9589c8f..28a87ae7f17 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -10,6 +10,8 @@ import io.swagger.models.HttpMethod; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; +import io.swagger.models.parameters.BodyParameter; +import io.swagger.models.parameters.FormParameter; import io.swagger.models.properties.*; import io.swagger.util.Yaml; @@ -36,6 +38,8 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf public FlaskConnexionCodegen() { super(); + modelPackage = "models"; + testPackage = "test"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); @@ -68,6 +72,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf apiTemplateFiles.put("controller.mustache", ".py"); modelTemplateFiles.put("model.mustache", ".py"); + apiTestTemplateFiles().put("controller_test.mustache", ".py"); /* * Template Location. This is the location which templates will be read from. The generator @@ -167,6 +172,11 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf modelPackage, "base_model_.py") ); + + supportingFiles.add(new SupportingFile("__init__test.mustache", + testPackage, + "__init__.py") + ); } private static String dropDots(String str) { @@ -178,6 +188,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return controllerPackage; } + /** * Configures the type of generator. * @@ -225,6 +236,11 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return underscore(toApiName(name)); } + @Override + public String toApiTestFilename(String name) { + return "test_" + toApiFilename(name); + } + /** * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping * those terms here. This logic is only called if a variable matches the reseved words @@ -275,7 +291,6 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return type; } - @Override public void preprocessSwagger(Swagger swagger) { // need vendor extensions for x-swagger-router-controller @@ -513,6 +528,93 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return null; } + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equalsIgnoreCase(type) || "str".equalsIgnoreCase(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "'" + escapeText(example) + "'"; + } else if ("Integer".equals(type) || "int".equals(type)) { + if(p.minimum != null) { + example = "" + (p.minimum.intValue() + 1); + } + if(p.maximum != null) { + example = "" + p.maximum.intValue(); + } else if (example == null) { + example = "56"; + } + + } else if ("Long".equalsIgnoreCase(type)) { + if(p.minimum != null) { + example = "" + (p.minimum.longValue() + 1); + } + if(p.maximum != null) { + example = "" + p.maximum.longValue(); + } else if (example == null) { + example = "789"; + } + } else if ("Float".equalsIgnoreCase(type) || "Double".equalsIgnoreCase(type)) { + if(p.minimum != null) { + example = "" + p.minimum; + } else if(p.maximum != null) { + example = "" + p.maximum; + } else if (example == null) { + example = "3.4"; + } + } else if ("BOOLEAN".equalsIgnoreCase(type) || "bool".equalsIgnoreCase(type)) { + if (example == null) { + example = "True"; + } + } else if ("file".equalsIgnoreCase(type)) { + example = "(BytesIO(b'some file data'), 'file.txt')"; + } else if ("Date".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20"; + } + example = "'" + escapeText(example) + "'"; + } else if ("DateTime".equalsIgnoreCase(type)) { + if (example == null) { + example = "2013-10-20T19:20:30+01:00"; + } + example = "'" + escapeText(example) + "'"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = type + "()"; + } else { + LOGGER.warn("Type " + type + " not handled properly in setParameterExampleValue"); + } + + if(p.items != null && p.items.defaultValue != null) { + example = p.items.defaultValue; + } + if (example == null) { + example = "None"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + if (Boolean.TRUE.equals(p.isBodyParam)) { + example = "[" + example + "]"; + } + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "{'key': " + example + "}"; + } + + p.example = example; + } + + @Override public String escapeQuotationMark(String input) { // remove ' to avoid code injection diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index e037cf1fe15..2d64ddbccf6 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -11,11 +11,11 @@ To run the server, please execute the following: ``` {{#supportPython2}} -sudo pip install -U connexion typing # install Connexion and Typing from PyPI +sudo pip install -U connexion flask_testing typing # install Connexion from PyPI python app.py {{/supportPython2}} {{^supportPython2}} -sudo pip3 install -U connexion # install Connexion from PyPI +sudo pip3 install -U connexion flask_testing # install Connexion from PyPI python3 app.py {{/supportPython2}} ``` diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache new file mode 100644 index 00000000000..352991098f1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache @@ -0,0 +1,14 @@ +from flask_testing import TestCase +from app import JSONEncoder +import connexion +import logging + + +class BaseTestCase(TestCase): + + def create_app(self): + logging.getLogger('connexion.operation').setLevel('ERROR') + app = connexion.App(__name__, specification_dir='../swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml') + return app.app diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache new file mode 100644 index 00000000000..92024849418 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller_test.mustache @@ -0,0 +1,49 @@ +# coding: utf-8 + +from __future__ import absolute_import + +{{#imports}}{{import}} +{{/imports}} +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class {{#operations}}Test{{classname}}(BaseTestCase): + """ {{classname}} integration test stubs """ + + {{#operation}} + def test_{{operationId}}(self): + """ + Test case for {{{operationId}}} + + {{{summary}}} + """ + {{#bodyParam}} + {{paramName}} = {{{example}}} + {{/bodyParam}} + {{#queryParams}} + {{#-first}}query_string = [{{/-first}}{{^-first}} {{/-first}}('{{paramName}}', {{{example}}}){{#hasMore}},{{/hasMore}}{{#-last}}]{{/-last}} + {{/queryParams}} + {{#headerParams}} + {{#-first}}headers = [{{/-first}}{{^-first}} {{/-first}}('{{paramName}}', {{{example}}}){{#hasMore}},{{/hasMore}}{{#-last}}]{{/-last}} + {{/headerParams}} + {{#formParams}} + {{#-first}}data = dict({{/-first}}{{^-first}} {{/-first}}{{paramName}}={{{example}}}{{#hasMore}},{{/hasMore}}{{#-last}}){{/-last}} + {{/formParams}} + response = self.client.open('{{#contextPath}}{{.}}{{/contextPath}}{{path}}'{{#pathParams}}{{#-first}}.format({{/-first}}{{paramName}}={{{example}}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/pathParams}}, + method='{{httpMethod}}'{{#bodyParam}}, + data=json.dumps({{paramName}}){{^consumes}}, + content_type='application/json'{{/consumes}}{{/bodyParam}}{{#headerParams}}{{#-first}}, + headers=headers{{/-first}}{{/headerParams}}{{#formParams}}{{#-first}}, + data=data{{/-first}}{{/formParams}}{{#consumes}}{{#-first}}, + content_type='{{{mediaType}}}'{{/-first}}{{/consumes}}{{#queryParams}}{{#-first}}, + query_string=query_string{{/-first}}{{/queryParams}}) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + {{/operation}} +{{/operations}} + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion-python2/README.md b/samples/server/petstore/flaskConnexion-python2/README.md index da392f1dd02..b744fc39f9a 100644 --- a/samples/server/petstore/flaskConnexion-python2/README.md +++ b/samples/server/petstore/flaskConnexion-python2/README.md @@ -10,7 +10,7 @@ This example uses the [Connexion](https://github.com/zalando/connexion) library To run the server, please execute the following: ``` -sudo pip install -U connexion typing # install Connexion and Typing from PyPI +sudo pip install -U connexion flask_testing typing # install Connexion from PyPI python app.py ``` diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py index 461f6163a63..bd37fffc4f5 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py @@ -1,6 +1,6 @@ import connexion -from models.pet import Pet from models.api_response import ApiResponse +from models.pet import Pet from datetime import date, datetime from typing import List, Dict from six import iteritems diff --git a/samples/server/petstore/flaskConnexion-python2/test/__init__.py b/samples/server/petstore/flaskConnexion-python2/test/__init__.py new file mode 100644 index 00000000000..352991098f1 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/test/__init__.py @@ -0,0 +1,14 @@ +from flask_testing import TestCase +from app import JSONEncoder +import connexion +import logging + + +class BaseTestCase(TestCase): + + def create_app(self): + logging.getLogger('connexion.operation').setLevel('ERROR') + app = connexion.App(__name__, specification_dir='../swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml') + return app.app diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py new file mode 100644 index 00000000000..50f0b523246 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.api_response import ApiResponse +from models.pet import Pet +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestPetController(BaseTestCase): + """ PetController integration test stubs """ + + def test_add_pet(self): + """ + Test case for add_pet + + Add a new pet to the store + """ + body = Pet() + response = self.client.open('/v2/pet', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_delete_pet(self): + """ + Test case for delete_pet + + Deletes a pet + """ + headers = [('apiKey', 'apiKey_example')] + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='DELETE', + headers=headers) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_find_pets_by_status(self): + """ + Test case for find_pets_by_status + + Finds Pets by status + """ + query_string = [('status', 'available')] + response = self.client.open('/v2/pet/findByStatus', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_find_pets_by_tags(self): + """ + Test case for find_pets_by_tags + + Finds Pets by tags + """ + query_string = [('tags', 'tags_example')] + response = self.client.open('/v2/pet/findByTags', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_pet_by_id(self): + """ + Test case for get_pet_by_id + + Find pet by ID + """ + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_pet(self): + """ + Test case for update_pet + + Update an existing pet + """ + body = Pet() + response = self.client.open('/v2/pet', + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_pet_with_form(self): + """ + Test case for update_pet_with_form + + Updates a pet in the store with form data + """ + data = dict(name='name_example', + status='status_example') + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='POST', + data=data, + content_type='application/x-www-form-urlencoded') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_upload_file(self): + """ + Test case for upload_file + + uploads an image + """ + data = dict(additionalMetadata='additionalMetadata_example', + file=(BytesIO(b'some file data'), 'file.txt')) + response = self.client.open('/v2/pet/{petId}/uploadImage'.format(petId=789), + method='POST', + data=data, + content_type='multipart/form-data') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py b/samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py new file mode 100644 index 00000000000..33a007ae195 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.order import Order +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestStoreController(BaseTestCase): + """ StoreController integration test stubs """ + + def test_delete_order(self): + """ + Test case for delete_order + + Delete purchase order by ID + """ + response = self.client.open('/v2/store/order/{orderId}'.format(orderId='orderId_example'), + method='DELETE') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_inventory(self): + """ + Test case for get_inventory + + Returns pet inventories by status + """ + response = self.client.open('/v2/store/inventory', + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_order_by_id(self): + """ + Test case for get_order_by_id + + Find purchase order by ID + """ + response = self.client.open('/v2/store/order/{orderId}'.format(orderId=5), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_place_order(self): + """ + Test case for place_order + + Place an order for a pet + """ + body = Order() + response = self.client.open('/v2/store/order', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py b/samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py new file mode 100644 index 00000000000..52dacf3df32 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.user import User +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestUserController(BaseTestCase): + """ UserController integration test stubs """ + + def test_create_user(self): + """ + Test case for create_user + + Create user + """ + body = User() + response = self.client.open('/v2/user', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_create_users_with_array_input(self): + """ + Test case for create_users_with_array_input + + Creates list of users with given input array + """ + body = [User()] + response = self.client.open('/v2/user/createWithArray', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_create_users_with_list_input(self): + """ + Test case for create_users_with_list_input + + Creates list of users with given input array + """ + body = [User()] + response = self.client.open('/v2/user/createWithList', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_delete_user(self): + """ + Test case for delete_user + + Delete user + """ + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='DELETE') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_user_by_name(self): + """ + Test case for get_user_by_name + + Get user by user name + """ + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_login_user(self): + """ + Test case for login_user + + Logs user into the system + """ + query_string = [('username', 'username_example'), + ('password', 'password_example')] + response = self.client.open('/v2/user/login', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_logout_user(self): + """ + Test case for logout_user + + Logs out current logged in user session + """ + response = self.client.open('/v2/user/logout', + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_user(self): + """ + Test case for update_user + + Updated user + """ + body = User() + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion/README.md b/samples/server/petstore/flaskConnexion/README.md index 933d4ec2723..0ba312c48ac 100644 --- a/samples/server/petstore/flaskConnexion/README.md +++ b/samples/server/petstore/flaskConnexion/README.md @@ -10,7 +10,7 @@ This example uses the [Connexion](https://github.com/zalando/connexion) library To run the server, please execute the following: ``` -sudo pip3 install -U connexion # install Connexion from PyPI +sudo pip3 install -U connexion flask_testing # install Connexion from PyPI python3 app.py ``` diff --git a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py index 461f6163a63..bd37fffc4f5 100644 --- a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py @@ -1,6 +1,6 @@ import connexion -from models.pet import Pet from models.api_response import ApiResponse +from models.pet import Pet from datetime import date, datetime from typing import List, Dict from six import iteritems diff --git a/samples/server/petstore/flaskConnexion/test/__init__.py b/samples/server/petstore/flaskConnexion/test/__init__.py new file mode 100644 index 00000000000..352991098f1 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/test/__init__.py @@ -0,0 +1,14 @@ +from flask_testing import TestCase +from app import JSONEncoder +import connexion +import logging + + +class BaseTestCase(TestCase): + + def create_app(self): + logging.getLogger('connexion.operation').setLevel('ERROR') + app = connexion.App(__name__, specification_dir='../swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml') + return app.app diff --git a/samples/server/petstore/flaskConnexion/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion/test/test_pet_controller.py new file mode 100644 index 00000000000..50f0b523246 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/test/test_pet_controller.py @@ -0,0 +1,118 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.api_response import ApiResponse +from models.pet import Pet +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestPetController(BaseTestCase): + """ PetController integration test stubs """ + + def test_add_pet(self): + """ + Test case for add_pet + + Add a new pet to the store + """ + body = Pet() + response = self.client.open('/v2/pet', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_delete_pet(self): + """ + Test case for delete_pet + + Deletes a pet + """ + headers = [('apiKey', 'apiKey_example')] + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='DELETE', + headers=headers) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_find_pets_by_status(self): + """ + Test case for find_pets_by_status + + Finds Pets by status + """ + query_string = [('status', 'available')] + response = self.client.open('/v2/pet/findByStatus', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_find_pets_by_tags(self): + """ + Test case for find_pets_by_tags + + Finds Pets by tags + """ + query_string = [('tags', 'tags_example')] + response = self.client.open('/v2/pet/findByTags', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_pet_by_id(self): + """ + Test case for get_pet_by_id + + Find pet by ID + """ + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_pet(self): + """ + Test case for update_pet + + Update an existing pet + """ + body = Pet() + response = self.client.open('/v2/pet', + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_pet_with_form(self): + """ + Test case for update_pet_with_form + + Updates a pet in the store with form data + """ + data = dict(name='name_example', + status='status_example') + response = self.client.open('/v2/pet/{petId}'.format(petId=789), + method='POST', + data=data, + content_type='application/x-www-form-urlencoded') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_upload_file(self): + """ + Test case for upload_file + + uploads an image + """ + data = dict(additionalMetadata='additionalMetadata_example', + file=(BytesIO(b'some file data'), 'file.txt')) + response = self.client.open('/v2/pet/{petId}/uploadImage'.format(petId=789), + method='POST', + data=data, + content_type='multipart/form-data') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion/test/test_store_controller.py b/samples/server/petstore/flaskConnexion/test/test_store_controller.py new file mode 100644 index 00000000000..33a007ae195 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/test/test_store_controller.py @@ -0,0 +1,60 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.order import Order +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestStoreController(BaseTestCase): + """ StoreController integration test stubs """ + + def test_delete_order(self): + """ + Test case for delete_order + + Delete purchase order by ID + """ + response = self.client.open('/v2/store/order/{orderId}'.format(orderId='orderId_example'), + method='DELETE') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_inventory(self): + """ + Test case for get_inventory + + Returns pet inventories by status + """ + response = self.client.open('/v2/store/inventory', + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_order_by_id(self): + """ + Test case for get_order_by_id + + Find purchase order by ID + """ + response = self.client.open('/v2/store/order/{orderId}'.format(orderId=5), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_place_order(self): + """ + Test case for place_order + + Place an order for a pet + """ + body = Order() + response = self.client.open('/v2/store/order', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() diff --git a/samples/server/petstore/flaskConnexion/test/test_user_controller.py b/samples/server/petstore/flaskConnexion/test/test_user_controller.py new file mode 100644 index 00000000000..52dacf3df32 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/test/test_user_controller.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +from __future__ import absolute_import + +from models.user import User +from . import BaseTestCase +from six import BytesIO +from flask import json + + +class TestUserController(BaseTestCase): + """ UserController integration test stubs """ + + def test_create_user(self): + """ + Test case for create_user + + Create user + """ + body = User() + response = self.client.open('/v2/user', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_create_users_with_array_input(self): + """ + Test case for create_users_with_array_input + + Creates list of users with given input array + """ + body = [User()] + response = self.client.open('/v2/user/createWithArray', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_create_users_with_list_input(self): + """ + Test case for create_users_with_list_input + + Creates list of users with given input array + """ + body = [User()] + response = self.client.open('/v2/user/createWithList', + method='POST', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_delete_user(self): + """ + Test case for delete_user + + Delete user + """ + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='DELETE') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_get_user_by_name(self): + """ + Test case for get_user_by_name + + Get user by user name + """ + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_login_user(self): + """ + Test case for login_user + + Logs user into the system + """ + query_string = [('username', 'username_example'), + ('password', 'password_example')] + response = self.client.open('/v2/user/login', + method='GET', + query_string=query_string) + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_logout_user(self): + """ + Test case for logout_user + + Logs out current logged in user session + """ + response = self.client.open('/v2/user/logout', + method='GET') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + def test_update_user(self): + """ + Test case for update_user + + Updated user + """ + body = User() + response = self.client.open('/v2/user/{username}'.format(username='username_example'), + method='PUT', + data=json.dumps(body), + content_type='application/json') + self.assert200(response, "Response body is : " + response.data.decode('utf-8')) + + +if __name__ == '__main__': + import unittest + unittest.main() From 89ee2b1c91265ed48d6c6a2a6a8a366cd53df64b Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 19 Nov 2016 11:41:59 +0100 Subject: [PATCH 084/269] fix JDK 1.7 issue with generics by casting to Set #2549 --- .../Java/libraries/okhttp-gson/api.mustache | 442 +++++++++--------- 1 file changed, 221 insertions(+), 221 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index f9834e40dfd..04c3918f260 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -1,221 +1,221 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiCallback; -import {{invokerPackage}}.ApiClient; -import {{invokerPackage}}.ApiException; -import {{invokerPackage}}.ApiResponse; -import {{invokerPackage}}.Configuration; -import {{invokerPackage}}.Pair; -import {{invokerPackage}}.ProgressRequestBody; -import {{invokerPackage}}.ProgressResponseBody; -{{#performBeanValidation}} -import {{invokerPackage}}.BeanValidationException; -{{/performBeanValidation}} - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{#performBeanValidation}} -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.executable.ExecutableValidator; -import java.util.Set; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -{{/performBeanValidation}} - -{{#imports}}import {{import}}; -{{/imports}} - -import java.lang.reflect.Type; -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -{{#operations}} -public class {{classname}} { - private ApiClient {{localVariablePrefix}}apiClient; - - public {{classname}}() { - this(Configuration.getDefaultApiClient()); - } - - public {{classname}}(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - public ApiClient getApiClient() { - return {{localVariablePrefix}}apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - {{#operation}} - /* Build call for {{operationId}} */ - private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - - // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} - - final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); - if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); - - final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); - {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - {{^performBeanValidation}} - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); - } - {{/required}}{{/allParams}} - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - {{/performBeanValidation}} - {{#performBeanValidation}} - try { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - ExecutableValidator executableValidator = factory.getValidator().forExecutables(); - - Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; - Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); - Set> violations = executableValidator.validateParameters(this, method, - parameterValues); - - if (violations.size() == 0) { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - } else { - Set> violationsObj = (Set>) violations; - throw new BeanValidationException(violationsObj); - } - } catch (NoSuchMethodException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } catch (SecurityException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } - - {{/performBeanValidation}} - - - - - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{returnType}}{{/returnType}} - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} - return {{localVariablePrefix}}resp.getData();{{/returnType}} - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} - } - - /** - * {{summary}} (asynchronously) - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} - return {{localVariablePrefix}}call; - } - {{/operation}} -} -{{/operations}} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiResponse; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ProgressRequestBody; +import {{invokerPackage}}.ProgressResponseBody; +{{#performBeanValidation}} +import {{invokerPackage}}.BeanValidationException; +{{/performBeanValidation}} + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{#performBeanValidation}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; +import java.util.Set; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +{{/performBeanValidation}} + +{{#imports}}import {{import}}; +{{/imports}} + +import java.lang.reflect.Type; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{operationId}} */ + private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + + // create path and map variables + String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); + if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); + + final String[] {{localVariablePrefix}}localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); + {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + {{^performBeanValidation}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + {{/performBeanValidation}} + {{#performBeanValidation}} + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ExecutableValidator executableValidator = factory.getValidator().forExecutables(); + + Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; + Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); + Set> violations = executableValidator.validateParameters(this, method, + parameterValues); + + if (violations.size() == 0) { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + } else { + throw new BeanValidationException((Set) violations); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } catch (SecurityException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } + + {{/performBeanValidation}} + + + + + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} +} +{{/operations}} From e4f27bc7a74f18ca8ca330e330960f854647e71d Mon Sep 17 00:00:00 2001 From: jfiala Date: Sat, 19 Nov 2016 11:55:22 +0100 Subject: [PATCH 085/269] make test invocations compileable #2549 --- .../src/main/resources/Java/api_test.mustache | 88 ++++++++++--------- 1 file changed, 45 insertions(+), 43 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache index 0a7639e0ec1..4ff7c577ac0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache @@ -1,43 +1,45 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiException; -{{#imports}}import {{import}}; -{{/imports}} -import org.junit.Test; - -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -/** - * API tests for {{classname}} - */ -public class {{classname}}Test { - - private final {{classname}} api = new {{classname}}(); - - {{#operations}}{{#operation}} - /** - * {{summary}} - * - * {{notes}} - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void {{operationId}}Test() throws ApiException { - {{#allParams}} - {{{dataType}}} {{paramName}} = null; - {{/allParams}} - // {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - // TODO: test validations - } - {{/operation}}{{/operations}} -} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +@Ignore +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} From 5a2ec035494fd722aa1509f5e155230b62841d74 Mon Sep 17 00:00:00 2001 From: Jordan Yaker Date: Sat, 19 Nov 2016 14:56:39 -0500 Subject: [PATCH 086/269] fix(javascript): added check to see if the parsed response is really empty. --- .../resources/Javascript/ApiClient.mustache | 2 +- .../petstore/javascript-promise/README.md | 1 + .../javascript-promise/docs/EnumTest.md | 1 + .../javascript-promise/docs/OuterEnum.md | 12 ++++ .../javascript-promise/src/ApiClient.js | 2 +- .../petstore/javascript-promise/src/index.js | 11 +++- .../javascript-promise/src/model/EnumTest.js | 16 +++-- .../javascript-promise/src/model/OuterEnum.js | 66 +++++++++++++++++++ .../test/model/OuterEnum.spec.js | 58 ++++++++++++++++ samples/client/petstore/javascript/README.md | 1 + .../petstore/javascript/docs/EnumTest.md | 1 + .../petstore/javascript/docs/OuterEnum.md | 12 ++++ .../petstore/javascript/src/ApiClient.js | 2 +- .../client/petstore/javascript/src/index.js | 11 +++- .../petstore/javascript/src/model/EnumTest.js | 16 +++-- .../javascript/src/model/OuterEnum.js | 66 +++++++++++++++++++ .../javascript/test/model/OuterEnum.spec.js | 58 ++++++++++++++++ 17 files changed, 319 insertions(+), 17 deletions(-) create mode 100644 samples/client/petstore/javascript-promise/docs/OuterEnum.md create mode 100644 samples/client/petstore/javascript-promise/src/model/OuterEnum.js create mode 100644 samples/client/petstore/javascript-promise/test/model/OuterEnum.spec.js create mode 100644 samples/client/petstore/javascript/docs/OuterEnum.md create mode 100644 samples/client/petstore/javascript/src/model/OuterEnum.js create mode 100644 samples/client/petstore/javascript/test/model/OuterEnum.spec.js diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index d277079892c..3cb405b6d71 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -309,7 +309,7 @@ // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null) { + if (data == null || !Object.keys(data).length) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 051eb9bf4ff..4a43f5c06e5 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -122,6 +122,7 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.Name](docs/Name.md) - [SwaggerPetstore.NumberOnly](docs/NumberOnly.md) - [SwaggerPetstore.Order](docs/Order.md) + - [SwaggerPetstore.OuterEnum](docs/OuterEnum.md) - [SwaggerPetstore.Pet](docs/Pet.md) - [SwaggerPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/javascript-promise/docs/EnumTest.md b/samples/client/petstore/javascript-promise/docs/EnumTest.md index f66f900778e..c907dac4951 100644 --- a/samples/client/petstore/javascript-promise/docs/EnumTest.md +++ b/samples/client/petstore/javascript-promise/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **enumString** | **String** | | [optional] **enumInteger** | **Number** | | [optional] **enumNumber** | **Number** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/javascript-promise/docs/OuterEnum.md b/samples/client/petstore/javascript-promise/docs/OuterEnum.md new file mode 100644 index 00000000000..4caf04ae09d --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/OuterEnum.md @@ -0,0 +1,12 @@ +# SwaggerPetstore.OuterEnum + +## Enum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index dc9dc139dfc..25cb11e4d73 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -312,7 +312,7 @@ // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null) { + if (data == null || !Object.keys(data).length) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index 9c59c8e541f..5f524f02ea3 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -179,6 +179,11 @@ * @property {module:model/Order} */ Order: Order, + /** + * The OuterEnum model constructor. + * @property {module:model/OuterEnum} + */ + OuterEnum: OuterEnum, /** * The Pet model constructor. * @property {module:model/Pet} diff --git a/samples/client/petstore/javascript-promise/src/model/EnumTest.js b/samples/client/petstore/javascript-promise/src/model/EnumTest.js index 9c3b596271d..077ebcd470b 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumTest.js @@ -14,18 +14,18 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient'], factory); + define(['ApiClient', 'model/OuterEnum'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')); + module.exports = factory(require('../ApiClient'), require('./OuterEnum')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.EnumTest = factory(root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.EnumTest = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.OuterEnum); } -}(this, function(ApiClient) { +}(this, function(ApiClient, OuterEnum) { 'use strict'; @@ -48,6 +48,7 @@ + }; /** @@ -70,6 +71,9 @@ if (data.hasOwnProperty('enum_number')) { obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); } + if (data.hasOwnProperty('outerEnum')) { + obj['outerEnum'] = OuterEnum.constructFromObject(data['outerEnum']); + } } return obj; } @@ -86,6 +90,10 @@ * @member {module:model/EnumTest.EnumNumberEnum} enum_number */ exports.prototype['enum_number'] = undefined; + /** + * @member {module:model/OuterEnum} outerEnum + */ + exports.prototype['outerEnum'] = undefined; /** diff --git a/samples/client/petstore/javascript-promise/src/model/OuterEnum.js b/samples/client/petstore/javascript-promise/src/model/OuterEnum.js new file mode 100644 index 00000000000..8a31a9d87be --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/OuterEnum.js @@ -0,0 +1,66 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.OuterEnum = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + /** + * Enum class OuterEnum. + * @enum {} + * @readonly + */ + var exports = { + /** + * value: "placed" + * @const + */ + "placed": "placed", + /** + * value: "approved" + * @const + */ + "approved": "approved", + /** + * value: "delivered" + * @const + */ + "delivered": "delivered" }; + + /** + * Returns a OuterEnum enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnum} The enum OuterEnum value. + */ + exports.constructFromObject = function(object) { + return exports[object]; + } + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/test/model/OuterEnum.spec.js b/samples/client/petstore/javascript-promise/test/model/OuterEnum.spec.js new file mode 100644 index 00000000000..14c26a3aef5 --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/OuterEnum.spec.js @@ -0,0 +1,58 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnum', function() { + it('should create an instance of OuterEnum', function() { + // uncomment below and update the code to test OuterEnum + //var instane = new SwaggerPetstore.OuterEnum(); + //expect(instance).to.be.a(SwaggerPetstore.OuterEnum); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 0a54168dd7c..69d3934db95 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -125,6 +125,7 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.Name](docs/Name.md) - [SwaggerPetstore.NumberOnly](docs/NumberOnly.md) - [SwaggerPetstore.Order](docs/Order.md) + - [SwaggerPetstore.OuterEnum](docs/OuterEnum.md) - [SwaggerPetstore.Pet](docs/Pet.md) - [SwaggerPetstore.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SwaggerPetstore.SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/javascript/docs/EnumTest.md b/samples/client/petstore/javascript/docs/EnumTest.md index f66f900778e..c907dac4951 100644 --- a/samples/client/petstore/javascript/docs/EnumTest.md +++ b/samples/client/petstore/javascript/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **enumString** | **String** | | [optional] **enumInteger** | **Number** | | [optional] **enumNumber** | **Number** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/javascript/docs/OuterEnum.md b/samples/client/petstore/javascript/docs/OuterEnum.md new file mode 100644 index 00000000000..4caf04ae09d --- /dev/null +++ b/samples/client/petstore/javascript/docs/OuterEnum.md @@ -0,0 +1,12 @@ +# SwaggerPetstore.OuterEnum + +## Enum + + +* `placed` (value: `"placed"`) + +* `approved` (value: `"approved"`) + +* `delivered` (value: `"delivered"`) + + diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 967da24892a..cf3fe731cf6 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -312,7 +312,7 @@ // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null) { + if (data == null || !Object.keys(data).length) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 9c59c8e541f..5f524f02ea3 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -179,6 +179,11 @@ * @property {module:model/Order} */ Order: Order, + /** + * The OuterEnum model constructor. + * @property {module:model/OuterEnum} + */ + OuterEnum: OuterEnum, /** * The Pet model constructor. * @property {module:model/Pet} diff --git a/samples/client/petstore/javascript/src/model/EnumTest.js b/samples/client/petstore/javascript/src/model/EnumTest.js index 9c3b596271d..077ebcd470b 100644 --- a/samples/client/petstore/javascript/src/model/EnumTest.js +++ b/samples/client/petstore/javascript/src/model/EnumTest.js @@ -14,18 +14,18 @@ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient'], factory); + define(['ApiClient', 'model/OuterEnum'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')); + module.exports = factory(require('../ApiClient'), require('./OuterEnum')); } else { // Browser globals (root is window) if (!root.SwaggerPetstore) { root.SwaggerPetstore = {}; } - root.SwaggerPetstore.EnumTest = factory(root.SwaggerPetstore.ApiClient); + root.SwaggerPetstore.EnumTest = factory(root.SwaggerPetstore.ApiClient, root.SwaggerPetstore.OuterEnum); } -}(this, function(ApiClient) { +}(this, function(ApiClient, OuterEnum) { 'use strict'; @@ -48,6 +48,7 @@ + }; /** @@ -70,6 +71,9 @@ if (data.hasOwnProperty('enum_number')) { obj['enum_number'] = ApiClient.convertToType(data['enum_number'], 'Number'); } + if (data.hasOwnProperty('outerEnum')) { + obj['outerEnum'] = OuterEnum.constructFromObject(data['outerEnum']); + } } return obj; } @@ -86,6 +90,10 @@ * @member {module:model/EnumTest.EnumNumberEnum} enum_number */ exports.prototype['enum_number'] = undefined; + /** + * @member {module:model/OuterEnum} outerEnum + */ + exports.prototype['outerEnum'] = undefined; /** diff --git a/samples/client/petstore/javascript/src/model/OuterEnum.js b/samples/client/petstore/javascript/src/model/OuterEnum.js new file mode 100644 index 00000000000..8a31a9d87be --- /dev/null +++ b/samples/client/petstore/javascript/src/model/OuterEnum.js @@ -0,0 +1,66 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.OuterEnum = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + /** + * Enum class OuterEnum. + * @enum {} + * @readonly + */ + var exports = { + /** + * value: "placed" + * @const + */ + "placed": "placed", + /** + * value: "approved" + * @const + */ + "approved": "approved", + /** + * value: "delivered" + * @const + */ + "delivered": "delivered" }; + + /** + * Returns a OuterEnum enum value from a Javascript object name. + * @param {Object} data The plain JavaScript object containing the name of the enum value. + * @return {module:model/OuterEnum} The enum OuterEnum value. + */ + exports.constructFromObject = function(object) { + return exports[object]; + } + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/test/model/OuterEnum.spec.js b/samples/client/petstore/javascript/test/model/OuterEnum.spec.js new file mode 100644 index 00000000000..14c26a3aef5 --- /dev/null +++ b/samples/client/petstore/javascript/test/model/OuterEnum.spec.js @@ -0,0 +1,58 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('OuterEnum', function() { + it('should create an instance of OuterEnum', function() { + // uncomment below and update the code to test OuterEnum + //var instane = new SwaggerPetstore.OuterEnum(); + //expect(instance).to.be.a(SwaggerPetstore.OuterEnum); + }); + + }); + +})); From 9322c8fb0eb19208727e269987e16245fa8f9eae Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 18 Nov 2016 16:42:57 +0100 Subject: [PATCH 087/269] [Flask] fix parameter naming --- .../languages/FlaskConnexionCodegen.java | 18 ++++++++++++++++-- .../controllers/pet_controller.py | 6 +++--- .../test/test_pet_controller.py | 2 +- .../controllers/pet_controller.py | 6 +++--- .../flaskConnexion/test/test_pet_controller.py | 2 +- 5 files changed, 24 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 28a87ae7f17..3df5b15d70c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -10,8 +10,7 @@ import io.swagger.models.HttpMethod; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; -import io.swagger.models.parameters.BodyParameter; -import io.swagger.models.parameters.FormParameter; +import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.*; import io.swagger.util.Yaml; @@ -317,6 +316,15 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf controllerPackage + "." + toApiFilename(tag) ); } + for (Parameter param: operation.getParameters()) { + // sanitize the param name but don't underscore it since it's used for request mapping + String name = param.getName(); + String paramName = sanitizeName(name); + if (!paramName.equals(name)) { + LOGGER.warn(name + " cannot be used as parameter name with flask-connexion and was sanitized as " + paramName); + } + param.setName(paramName); + } } } } @@ -405,6 +413,12 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf return name; } + @Override + public String toParamName(String name) { + // Param name is already sanitized in swagger spec processing + return name; + } + @Override public String toModelFilename(String name) { name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py index bd37fffc4f5..0a1be8f8863 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py @@ -21,14 +21,14 @@ def add_pet(body): return 'do some magic!' -def delete_pet(petId, apiKey=None): +def delete_pet(petId, api_key=None): """ Deletes a pet :param petId: Pet id to delete :type petId: int - :param apiKey: - :type apiKey: str + :param api_key: + :type api_key: str :rtype: None """ diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py index 50f0b523246..31e3b3fcb6b 100644 --- a/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py @@ -31,7 +31,7 @@ class TestPetController(BaseTestCase): Deletes a pet """ - headers = [('apiKey', 'apiKey_example')] + headers = [('api_key', 'api_key_example')] response = self.client.open('/v2/pet/{petId}'.format(petId=789), method='DELETE', headers=headers) diff --git a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py index bd37fffc4f5..0a1be8f8863 100644 --- a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/controllers/pet_controller.py @@ -21,14 +21,14 @@ def add_pet(body): return 'do some magic!' -def delete_pet(petId, apiKey=None): +def delete_pet(petId, api_key=None): """ Deletes a pet :param petId: Pet id to delete :type petId: int - :param apiKey: - :type apiKey: str + :param api_key: + :type api_key: str :rtype: None """ diff --git a/samples/server/petstore/flaskConnexion/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion/test/test_pet_controller.py index 50f0b523246..31e3b3fcb6b 100644 --- a/samples/server/petstore/flaskConnexion/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion/test/test_pet_controller.py @@ -31,7 +31,7 @@ class TestPetController(BaseTestCase): Deletes a pet """ - headers = [('apiKey', 'apiKey_example')] + headers = [('api_key', 'api_key_example')] response = self.client.open('/v2/pet/{petId}'.format(petId=789), method='DELETE', headers=headers) From e7e99eb69febad83e2565c050e5c953003360937 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 21 Nov 2016 00:38:01 +0800 Subject: [PATCH 088/269] add ErrorResponse as reserved word in Swift generators --- .../codegen/languages/Swift3Codegen.java | 20 +++++++++++-------- .../codegen/languages/SwiftCodegen.java | 4 ++++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 7bfdbf10e07..9869bd6e679 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -102,14 +102,18 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { ); reservedWords = new HashSet<>( Arrays.asList( - "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", - "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") + // name used by swift client + "ErrorResponse", + + // swift keywords + "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "Any", "Error", "URL", + "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak") ); typeMapping = new HashMap<>(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index b9595c163a6..f29de4f66bd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -101,6 +101,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { ); reservedWords = new HashSet( Arrays.asList( + // name used by swift client + "ErrorResponse", + + // swift keywords "Int", "Int32", "Int64", "Int64", "Float", "Double", "Bool", "Void", "String", "Character", "AnyObject", "class", "Class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", From 6ad38874c59b6a4d470586168c9e0d0f4efcd8ea Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 21 Nov 2016 00:43:41 +0800 Subject: [PATCH 089/269] [ObjC] version update for ISO8601 (#4220) * remove php apache license * update iso8601 version for objc client --- .../swagger-codegen/src/main/resources/objc/podspec.mustache | 2 +- samples/client/petstore/objc/core-data/SwaggerClient.podspec | 2 +- samples/client/petstore/objc/default/SwaggerClient.podspec | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 00284af58c5..e9979f04ae2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3.1' s.dependency 'JSONModel', '~> 1.4' - s.dependency 'ISO8601', '~> 0.5' + s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient.podspec b/samples/client/petstore/objc/core-data/SwaggerClient.podspec index 23a8f8b8106..1a31e2e9a15 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient.podspec +++ b/samples/client/petstore/objc/core-data/SwaggerClient.podspec @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3.1' s.dependency 'JSONModel', '~> 1.4' - s.dependency 'ISO8601', '~> 0.5' + s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/default/SwaggerClient.podspec b/samples/client/petstore/objc/default/SwaggerClient.podspec index 3f2aba3cdab..2587bd3375a 100644 --- a/samples/client/petstore/objc/default/SwaggerClient.podspec +++ b/samples/client/petstore/objc/default/SwaggerClient.podspec @@ -32,6 +32,6 @@ Pod::Spec.new do |s| s.dependency 'AFNetworking', '~> 3.1' s.dependency 'JSONModel', '~> 1.4' - s.dependency 'ISO8601', '~> 0.5' + s.dependency 'ISO8601', '~> 0.6' end From 76965594b9f2a3648b305d5abc2600016a13ff71 Mon Sep 17 00:00:00 2001 From: szakrewsky Date: Mon, 21 Nov 2016 04:03:26 -0500 Subject: [PATCH 090/269] Issue #2449 SubClass annotations are missing from the base class (#4085) * petstore up to latest * Issue #2449 SubClass annotations are missing from the base class * include child in all its super types --- .../java/io/swagger/codegen/CodegenModel.java | 1 + .../io/swagger/codegen/DefaultCodegen.java | 12 +++++++ .../languages/AbstractJavaCodegen.java | 6 ++++ .../src/main/resources/Java/pojo.mustache | 2 +- .../Java/typeInfoAnnotation.mustache | 5 +++ .../java/io/swagger/client/model/Animal.java | 7 +++- .../java/io/swagger/client/model/Animal.java | 7 +++- .../io/swagger/client/RFC3339DateFormat.java | 32 +++++++++++++++++++ .../java/io/swagger/client/model/Animal.java | 7 +++- .../java/io/swagger/client/model/Animal.java | 7 +++- 10 files changed, 81 insertions(+), 5 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/RFC3339DateFormat.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 118de425c93..6b0dd68e9fb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -17,6 +17,7 @@ public class CodegenModel { // References to parent and interface CodegenModels. Only set when code generator supports inheritance. public CodegenModel parentModel; public List interfaceModels; + public List children; public String name, classname, title, description, classVarName, modelJson, dataType; public String classFilename; // store the class file name, mainly used for import diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 8a9b8accd38..2eac677995c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -180,6 +180,18 @@ public class DefaultCodegen { } } } + // Let parent know about all its children + for (String name : allModels.keySet()) { + CodegenModel cm = allModels.get(name); + CodegenModel parent = allModels.get(cm.parent); + while (parent != null) { + if (parent.children == null) { + parent.children = new ArrayList(); + } + parent.children.add(cm); + parent = allModels.get(parent.parent); + } + } } return objs; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 5327a4e84cc..6e90afaf61a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -253,6 +253,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code importMapping.put("ApiModelProperty", "io.swagger.annotations.ApiModelProperty"); importMapping.put("ApiModel", "io.swagger.annotations.ApiModel"); importMapping.put("JsonProperty", "com.fasterxml.jackson.annotation.JsonProperty"); + importMapping.put("JsonSubTypes", "com.fasterxml.jackson.annotation.JsonSubTypes"); + importMapping.put("JsonTypeInfo", "com.fasterxml.jackson.annotation.JsonTypeInfo"); importMapping.put("JsonCreator", "com.fasterxml.jackson.annotation.JsonCreator"); importMapping.put("JsonValue", "com.fasterxml.jackson.annotation.JsonValue"); importMapping.put("SerializedName", "com.google.gson.annotations.SerializedName"); @@ -628,6 +630,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code if(codegenModel.description != null) { codegenModel.imports.add("ApiModel"); } + if (codegenModel.discriminator != null && additionalProperties.containsKey("jackson")) { + codegenModel.imports.add("JsonSubTypes"); + codegenModel.imports.add("JsonTypeInfo"); + } if (allDefinitions != null && codegenModel.parentSchema != null && codegenModel.hasEnums) { final Model parentModel = allDefinitions.get(codegenModel.parentSchema); final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index 408c6dbe645..c522bdba860 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -2,7 +2,7 @@ * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} -{{>generatedAnnotation}} +{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}} public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcelableModel}}implements Parcelable {{#serializableModel}}, Serializable {{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable {{/serializableModel}}{{/parcelableModel}}{ {{#vars}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..6ef9431ff60 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache @@ -0,0 +1,5 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}" ) +@JsonSubTypes({ + {{#children}}@JsonSubTypes.Type(value = {{name}}.class, name = "{{name}}"),{{/children}} +}){{/jackson}} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 485734d526c..8fc61b6891a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -16,13 +16,18 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Animal */ - +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 485734d526c..8fc61b6891a 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -16,13 +16,18 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Animal */ - +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..e8df24310aa --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java index 485734d526c..8fc61b6891a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -16,13 +16,18 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Animal */ - +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 485734d526c..8fc61b6891a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -16,13 +16,18 @@ package io.swagger.client.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * Animal */ - +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) public class Animal { @JsonProperty("className") private String className = null; From 515e723faed53ab53258519bd4919e3e66534f8e Mon Sep 17 00:00:00 2001 From: Martin McWhorter Date: Mon, 21 Nov 2016 11:39:07 +0000 Subject: [PATCH 091/269] Allow TypeScript noImplicitAny: true (#4205) * Allow TypeScript noImplicitAny: true * Update typescript-angular2 examples --- .../main/resources/typescript-angular2/api.mustache | 2 +- .../typescript-angular2/default/api/PetApi.ts | 12 ++++++------ .../typescript-angular2/default/api/StoreApi.ts | 2 +- .../typescript-angular2/default/api/UserApi.ts | 2 +- .../petstore/typescript-angular2/npm/README.md | 4 ++-- .../petstore/typescript-angular2/npm/api/PetApi.ts | 12 ++++++------ .../petstore/typescript-angular2/npm/api/StoreApi.ts | 2 +- .../petstore/typescript-angular2/npm/api/UserApi.ts | 2 +- .../petstore/typescript-angular2/npm/package.json | 2 +- 9 files changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 00a013f5675..fe745f03b10 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -44,7 +44,7 @@ export class {{classname}} { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 843a8af839e..b2feacfc4e1 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -49,7 +49,7 @@ export class PetApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; @@ -414,17 +414,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index b4847a56843..b3d6ea61e60 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -49,7 +49,7 @@ export class StoreApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 61abce21952..25f38a899a4 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -49,7 +49,7 @@ export class UserApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index d8589f3239f..bcf578d1297 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611161801 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611201817 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611161801 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611201817 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 843a8af839e..b2feacfc4e1 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -49,7 +49,7 @@ export class PetApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; @@ -414,17 +414,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index b4847a56843..b3d6ea61e60 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -49,7 +49,7 @@ export class StoreApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 61abce21952..25f38a899a4 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -49,7 +49,7 @@ export class UserApi { private extendObj(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; + (objA as any)[key] = (objB as any)[key]; } } return objA; diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index c50d15d6b0a..5f09b8f7a0f 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201611161801", + "version": "0.0.1-SNAPSHOT.201611201817", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 9dc809bdc7c6dca5dc4c71b9669e183ee755450f Mon Sep 17 00:00:00 2001 From: Ewan Mellor Date: Mon, 21 Nov 2016 08:19:17 -0800 Subject: [PATCH 092/269] Add two override points inside AlamofireRequestBuilder in the Swift 3 template. (#4170) * Add two override points inside AlamofireRequestBuilder in the Swift 3 template. These allow the caller to control the request configuration (e.g. to override the cache policy) and to control the Content-Type that is given to an uploaded form part. * Regenerate with ./bin/swift3-petstore-all.sh to match recent changes. This includes a few minor changes that weren't made in this branch, so this apparently wasn't run on master after some other recent changes. --- .../swift3/AlamofireImplementations.mustache | 28 +++++++++++++++++-- .../Swaggers/AlamofireImplementations.swift | 28 +++++++++++++++++-- .../Swaggers/AlamofireImplementations.swift | 28 +++++++++++++++++-- .../Swaggers/AlamofireImplementations.swift | 28 +++++++++++++++++-- 4 files changed, 104 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache index 03e421b7f10..2857c85889d 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache @@ -30,6 +30,25 @@ open class AlamofireRequestBuilder: RequestBuilder { return Alamofire.SessionManager(configuration: configuration) } + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding) + } + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { let managerId:String = UUID().uuidString // Create a new manager for each request to customize its request header @@ -47,7 +66,12 @@ open class AlamofireRequestBuilder: RequestBuilder { for (k, v) in self.parameters! { switch v { case let fileURL as URL: - mpForm.append(fileURL, withName: k) + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } break case let string as String: mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) @@ -72,7 +96,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } }) } else { - let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding) + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 03e421b7f10..2857c85889d 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -30,6 +30,25 @@ open class AlamofireRequestBuilder: RequestBuilder { return Alamofire.SessionManager(configuration: configuration) } + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding) + } + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { let managerId:String = UUID().uuidString // Create a new manager for each request to customize its request header @@ -47,7 +66,12 @@ open class AlamofireRequestBuilder: RequestBuilder { for (k, v) in self.parameters! { switch v { case let fileURL as URL: - mpForm.append(fileURL, withName: k) + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } break case let string as String: mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) @@ -72,7 +96,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } }) } else { - let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding) + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 03e421b7f10..2857c85889d 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -30,6 +30,25 @@ open class AlamofireRequestBuilder: RequestBuilder { return Alamofire.SessionManager(configuration: configuration) } + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding) + } + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { let managerId:String = UUID().uuidString // Create a new manager for each request to customize its request header @@ -47,7 +66,12 @@ open class AlamofireRequestBuilder: RequestBuilder { for (k, v) in self.parameters! { switch v { case let fileURL as URL: - mpForm.append(fileURL, withName: k) + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } break case let string as String: mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) @@ -72,7 +96,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } }) } else { - let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding) + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 03e421b7f10..2857c85889d 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -30,6 +30,25 @@ open class AlamofireRequestBuilder: RequestBuilder { return Alamofire.SessionManager(configuration: configuration) } + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the request + configuration (e.g. to override the cache policy). + */ + open func makeRequest(manager: SessionManager, method: HTTPMethod, encoding: ParameterEncoding) -> DataRequest { + return manager.request(URLString, method: method, parameters: parameters, encoding: encoding) + } + override open func execute(_ completion: @escaping (_ response: Response?, _ error: Error?) -> Void) { let managerId:String = UUID().uuidString // Create a new manager for each request to customize its request header @@ -47,7 +66,12 @@ open class AlamofireRequestBuilder: RequestBuilder { for (k, v) in self.parameters! { switch v { case let fileURL as URL: - mpForm.append(fileURL, withName: k) + if let mimeType = self.contentTypeForFormPart(fileURL: fileURL) { + mpForm.append(fileURL, withName: k, fileName: fileURL.lastPathComponent, mimeType: mimeType) + } + else { + mpForm.append(fileURL, withName: k) + } break case let string as String: mpForm.append(string.data(using: String.Encoding.utf8)!, withName: k) @@ -72,7 +96,7 @@ open class AlamofireRequestBuilder: RequestBuilder { } }) } else { - let request = manager.request(URLString, method: xMethod!, parameters: parameters, encoding: encoding) + let request = makeRequest(manager: manager, method: xMethod!, encoding: encoding) if let onProgressReady = self.onProgressReady { onProgressReady(request.progress) } From 1104ce8587f3a772ad336d9cb3efe16899f2f435 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 22 Nov 2016 10:02:29 +0800 Subject: [PATCH 093/269] add docker image for swagger-codegen-cli --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index fe693c57f37..9d52b8888d8 100644 --- a/README.md +++ b/README.md @@ -128,7 +128,8 @@ cd /vagrant #### Public Docker image -https://hub.docker.com/r/swaggerapi/swagger-generator/ + - https://hub.docker.com/r/swaggerapi/swagger-generator/ (official) + - https://hub.docker.com/r/jimschubert/swagger-codegen-cli/ (unofficial) ### Homebrew To install, run `brew install swagger-codegen` From 474dae08cf2ccbc8a2cf89d374cfa0b0cacfc1a9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 22 Nov 2016 10:42:15 +0800 Subject: [PATCH 094/269] update NodeJS readme to remove oudated doc (#4232) --- .../src/main/resources/nodejs/README.mustache | 6 +----- samples/server/petstore/nodejs/README.md | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache index 81628f81294..b8fd4cd80ab 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache @@ -1,11 +1,7 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. - -This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: - -[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. ### Running the server To run the server, run: diff --git a/samples/server/petstore/nodejs/README.md b/samples/server/petstore/nodejs/README.md index a4acae25a96..211055874d5 100644 --- a/samples/server/petstore/nodejs/README.md +++ b/samples/server/petstore/nodejs/README.md @@ -1,11 +1,7 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. This is an example of building a node.js server. - -This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: - -[README](https://github.com/swagger-api/swagger-codegen/blob/master/README.md) +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. ### Running the server To run the server, run: From fbc031562839b0294dd71cff2c1cb778d196ac5f Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 22 Nov 2016 10:44:32 +0800 Subject: [PATCH 095/269] add Balance Internet --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 9d52b8888d8..2af1980f877 100644 --- a/README.md +++ b/README.md @@ -749,6 +749,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) - [Avenida Compras S.A.](https://www.avenida.com.ar) +- [Balance Internet](https://www.balanceinternet.com.au/) - [beemo](http://www.beemo.eu) - [bitly](https://bitly.com) - [Bufferfly Network](https://www.butterflynetinc.com/) From 58b66a0b0a35b498379c40716b3e26b37ddce514 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 22 Nov 2016 23:01:41 +0800 Subject: [PATCH 096/269] python code style enhancement (#4238) --- .../src/main/resources/python/api.mustache | 44 ++-- .../main/resources/python/api_client.mustache | 2 +- .../src/main/resources/python/model.mustache | 11 +- .../src/main/resources/python/setup.mustache | 8 +- samples/client/petstore/python/README.md | 1 + .../client/petstore/python/docs/EnumTest.md | 1 + .../client/petstore/python/docs/OuterEnum.md | 9 + .../petstore/python/petstore_api/__init__.py | 1 + .../python/petstore_api/api_client.py | 2 +- .../python/petstore_api/apis/fake_api.py | 88 +++---- .../python/petstore_api/apis/pet_api.py | 228 ++++++++---------- .../python/petstore_api/apis/store_api.py | 113 ++++----- .../python/petstore_api/apis/user_api.py | 225 ++++++++--------- .../python/petstore_api/models/__init__.py | 1 + .../models/additional_properties_class.py | 5 - .../python/petstore_api/models/animal.py | 5 - .../petstore_api/models/api_response.py | 7 - .../models/array_of_array_of_number_only.py | 3 - .../models/array_of_number_only.py | 3 - .../python/petstore_api/models/array_test.py | 7 - .../python/petstore_api/models/cat.py | 7 - .../python/petstore_api/models/category.py | 5 - .../python/petstore_api/models/client.py | 3 - .../python/petstore_api/models/dog.py | 7 - .../python/petstore_api/models/enum_arrays.py | 5 - .../python/petstore_api/models/enum_test.py | 37 ++- .../python/petstore_api/models/format_test.py | 27 --- .../petstore_api/models/has_only_read_only.py | 5 - .../python/petstore_api/models/list.py | 3 - .../python/petstore_api/models/map_test.py | 5 - ...perties_and_additional_properties_class.py | 7 - .../petstore_api/models/model_200_response.py | 5 - .../petstore_api/models/model_return.py | 3 - .../python/petstore_api/models/name.py | 9 - .../python/petstore_api/models/number_only.py | 3 - .../python/petstore_api/models/order.py | 11 - .../python/petstore_api/models/outer_enum.py | 90 +++++++ .../python/petstore_api/models/pet.py | 11 - .../petstore_api/models/read_only_first.py | 5 - .../petstore_api/models/special_model_name.py | 3 - .../python/petstore_api/models/tag.py | 5 - .../python/petstore_api/models/user.py | 15 -- samples/client/petstore/python/setup.py | 2 - .../petstore/python/test/test_outer_enum.py | 42 ++++ .../petstore/python/tests/test_map_test.py | 1 - .../petstore/python/tests/test_pet_api.py | 6 +- samples/client/petstore/python/tests/util.py | 1 + 47 files changed, 518 insertions(+), 569 deletions(-) create mode 100644 samples/client/petstore/python/docs/OuterEnum.md create mode 100644 samples/client/petstore/python/petstore_api/models/outer_enum.py create mode 100644 samples/client/petstore/python/test/test_outer_enum.py diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index e3c687f7bad..f8b5d564ab6 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -35,9 +35,12 @@ class {{classname}}(object): def {{operationId}}(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): """ +{{#summary}} {{{summary}}} +{{/summary}} +{{#notes}} {{{notes}}} - +{{/notes}} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -54,7 +57,7 @@ class {{classname}}(object): :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} - :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} + :param {{dataType}} {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} If the method is called asynchronously, @@ -69,9 +72,12 @@ class {{classname}}(object): def {{operationId}}_with_http_info(self, {{#sortParamsByRequiredFlag}}{{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}{{/sortParamsByRequiredFlag}}**kwargs): """ +{{#summary}} {{{summary}}} +{{/summary}} +{{#notes}} {{{notes}}} - +{{/notes}} This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -88,7 +94,7 @@ class {{classname}}(object): :param callback function: The callback function for asynchronous request. (optional) {{#allParams}} - :param {{dataType}} {{paramName}}: {{{description}}}{{#required}} (required){{/required}}{{#optional}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/optional}} + :param {{dataType}} {{paramName}}:{{#description}} {{{description}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/optional}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} If the method is called asynchronously, @@ -149,8 +155,10 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, number of items must be greater than or equal to `{{minItems}}`") {{/minItems}} {{/hasValidation}} -{{/allParams}} +{{#-last}} +{{/-last}} +{{/allParams}} collection_formats = {} resource_path = '{{path}}'.replace('{format}', 'json') @@ -203,18 +211,18 @@ class {{classname}}(object): auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] return self.api_client.call_api(resource_path, '{{httpMethod}}', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index ea1e60723f0..6b1a7d7e61b 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -175,7 +175,7 @@ class ApiClient(object): for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 68e064bd190..171b7277f06 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -37,13 +37,14 @@ class {{classname}}(object): self._{{name}} = {{name}} {{/vars}} -{{#vars}}{{#-first}} -{{/-first}} +{{#vars}} @property def {{name}}(self): """ Gets the {{name}} of this {{classname}}. -{{#description}} {{{description}}}{{/description}} +{{#description}} + {{{description}}} +{{/description}} :return: The {{name}} of this {{classname}}. :rtype: {{datatype}} @@ -54,7 +55,9 @@ class {{classname}}(object): def {{name}}(self, {{name}}): """ Sets the {{name}} of this {{classname}}. -{{#description}} {{{description}}}{{/description}} +{{#description}} + {{{description}}} +{{/description}} :param {{name}}: The {{name}} of this {{classname}}. :type: {{datatype}} diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index 45606bf9474..6a1a4320f38 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -7,7 +7,9 @@ from setuptools import setup, find_packages NAME = "{{packageName}}" VERSION = "{{packageVersion}}" -{{#apiInfo}}{{#apis}}{{^hasMore}} +{{#apiInfo}} +{{#apis}} +{{^hasMore}} # To install the library, run the following # # python setup.py install @@ -31,4 +33,6 @@ setup( {{appDescription}} """ ) -{{/hasMore}}{{/apis}}{{/apiInfo}} +{{/hasMore}} +{{/apis}} +{{/apiInfo}} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 7b29cebd534..1c59d444ffc 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -120,6 +120,7 @@ Class | Method | HTTP request | Description - [Name](docs/Name.md) - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) + - [OuterEnum](docs/OuterEnum.md) - [Pet](docs/Pet.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/python/docs/EnumTest.md b/samples/client/petstore/python/docs/EnumTest.md index 38dd71f5b83..94dd4864629 100644 --- a/samples/client/petstore/python/docs/EnumTest.md +++ b/samples/client/petstore/python/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **enum_string** | **str** | | [optional] **enum_integer** | **int** | | [optional] **enum_number** | **float** | | [optional] +**outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/python/docs/OuterEnum.md b/samples/client/petstore/python/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/python/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index 954d02430ac..72c011b0f13 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -38,6 +38,7 @@ from .models.model_return import ModelReturn from .models.name import Name from .models.number_only import NumberOnly from .models.order import Order +from .models.outer_enum import OuterEnum from .models.pet import Pet from .models.read_only_first import ReadOnlyFirst from .models.special_model_name import SpecialModelName diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index 9d730daaf04..f5824c50572 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -184,7 +184,7 @@ class ApiClient(object): for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() else: diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 0d9f75f1789..3da6777bb3a 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -43,8 +43,6 @@ class FakeApi(object): def test_client_model(self, body, **kwargs): """ To test \"client\" model - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -70,8 +68,6 @@ class FakeApi(object): def test_client_model_with_http_info(self, body, **kwargs): """ To test \"client\" model - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -138,25 +134,24 @@ class FakeApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def test_endpoint_parameters(self, number, double, pattern_without_delimiter, byte, **kwargs): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -196,7 +191,6 @@ class FakeApi(object): """ Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -337,25 +331,23 @@ class FakeApi(object): auth_settings = ['http_basic_test'] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def test_enum_parameters(self, **kwargs): """ To test enum parameters - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -388,8 +380,6 @@ class FakeApi(object): def test_enum_parameters_with_http_info(self, **kwargs): """ To test enum parameters - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -477,16 +467,16 @@ class FakeApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index eda677c1956..d1e45a33def 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -44,7 +44,6 @@ class PetApi(object): """ Add a new pet to the store - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -71,7 +70,6 @@ class PetApi(object): """ Add a new pet to the store - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -138,25 +136,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def delete_pet(self, pet_id, **kwargs): """ Deletes a pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -168,7 +165,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) - :param str api_key: + :param str api_key: :return: None If the method is called asynchronously, returns the request thread. @@ -184,7 +181,6 @@ class PetApi(object): """ Deletes a pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -196,7 +192,7 @@ class PetApi(object): :param callback function: The callback function for asynchronous request. (optional) :param int pet_id: Pet id to delete (required) - :param str api_key: + :param str api_key: :return: None If the method is called asynchronously, returns the request thread. @@ -254,25 +250,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def find_pets_by_status(self, status, **kwargs): """ Finds Pets by status Multiple status values can be provided with comma separated strings - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -299,7 +294,6 @@ class PetApi(object): """ Finds Pets by status Multiple status values can be provided with comma separated strings - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -367,25 +361,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def find_pets_by_tags(self, tags, **kwargs): """ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -412,7 +405,6 @@ class PetApi(object): """ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -480,25 +472,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Pet]', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='list[Pet]', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def get_pet_by_id(self, pet_id, **kwargs): """ Find pet by ID Returns a single pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -525,7 +516,6 @@ class PetApi(object): """ Find pet by ID Returns a single pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -592,25 +582,24 @@ class PetApi(object): auth_settings = ['api_key'] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Pet', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Pet', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def update_pet(self, body, **kwargs): """ Update an existing pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -637,7 +626,6 @@ class PetApi(object): """ Update an existing pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -704,25 +692,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def update_pet_with_form(self, pet_id, **kwargs): """ Updates a pet in the store with form data - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -751,7 +738,6 @@ class PetApi(object): """ Updates a pet in the store with form data - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -824,25 +810,24 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def upload_file(self, pet_id, **kwargs): """ uploads an image - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -871,7 +856,6 @@ class PetApi(object): """ uploads an image - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -944,16 +928,16 @@ class PetApi(object): auth_settings = ['petstore_auth'] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ApiResponse', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='ApiResponse', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index a4a93141dd1..82a4eee9e35 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -44,7 +44,6 @@ class StoreApi(object): """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -71,7 +70,6 @@ class StoreApi(object): """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -140,25 +138,24 @@ class StoreApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def get_inventory(self, **kwargs): """ Returns pet inventories by status Returns a map of status codes to quantities - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -184,7 +181,6 @@ class StoreApi(object): """ Returns pet inventories by status Returns a map of status codes to quantities - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -216,7 +212,6 @@ class StoreApi(object): params[key] = val del params['kwargs'] - collection_formats = {} resource_path = '/store/inventory'.replace('{format}', 'json') @@ -245,25 +240,24 @@ class StoreApi(object): auth_settings = ['api_key'] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='dict(str, int)', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='dict(str, int)', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def get_order_by_id(self, order_id, **kwargs): """ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -290,7 +284,6 @@ class StoreApi(object): """ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -361,25 +354,24 @@ class StoreApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def place_order(self, body, **kwargs): """ Place an order for a pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -406,7 +398,6 @@ class StoreApi(object): """ Place an order for a pet - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -473,16 +464,16 @@ class StoreApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Order', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Order', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index e22c164c4ee..0ad16268c34 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -44,7 +44,6 @@ class UserApi(object): """ Create user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -71,7 +70,6 @@ class UserApi(object): """ Create user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -138,25 +136,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def create_users_with_array_input(self, body, **kwargs): """ Creates list of users with given input array - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -183,7 +180,6 @@ class UserApi(object): """ Creates list of users with given input array - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -250,25 +246,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def create_users_with_list_input(self, body, **kwargs): """ Creates list of users with given input array - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -295,7 +290,6 @@ class UserApi(object): """ Creates list of users with given input array - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -362,25 +356,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def delete_user(self, username, **kwargs): """ Delete user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -407,7 +400,6 @@ class UserApi(object): """ Delete user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -474,25 +466,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def get_user_by_name(self, username, **kwargs): """ Get user by user name - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -519,7 +510,6 @@ class UserApi(object): """ Get user by user name - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -586,25 +576,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='User', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='User', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def login_user(self, username, password, **kwargs): """ Logs user into the system - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -632,7 +621,6 @@ class UserApi(object): """ Logs user into the system - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -705,25 +693,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='str', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='str', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def logout_user(self, **kwargs): """ Logs out current logged in user session - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -749,7 +736,6 @@ class UserApi(object): """ Logs out current logged in user session - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -781,7 +767,6 @@ class UserApi(object): params[key] = val del params['kwargs'] - collection_formats = {} resource_path = '/user/logout'.replace('{format}', 'json') @@ -810,25 +795,24 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) def update_user(self, username, body, **kwargs): """ Updated user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -856,7 +840,6 @@ class UserApi(object): """ Updated user This can only be done by the logged in user. - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -929,16 +912,16 @@ class UserApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index ab05e679741..e8a9a6a8d69 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -38,6 +38,7 @@ from .model_return import ModelReturn from .name import Name from .number_only import NumberOnly from .order import Order +from .outer_enum import OuterEnum from .pet import Pet from .read_only_first import ReadOnlyFirst from .special_model_name import SpecialModelName diff --git a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py index 601be4c46f4..4840f52a8e8 100644 --- a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -43,13 +43,11 @@ class AdditionalPropertiesClass(object): self._map_property = map_property self._map_of_map_property = map_of_map_property - @property def map_property(self): """ Gets the map_property of this AdditionalPropertiesClass. - :return: The map_property of this AdditionalPropertiesClass. :rtype: dict(str, str) """ @@ -60,7 +58,6 @@ class AdditionalPropertiesClass(object): """ Sets the map_property of this AdditionalPropertiesClass. - :param map_property: The map_property of this AdditionalPropertiesClass. :type: dict(str, str) """ @@ -72,7 +69,6 @@ class AdditionalPropertiesClass(object): """ Gets the map_of_map_property of this AdditionalPropertiesClass. - :return: The map_of_map_property of this AdditionalPropertiesClass. :rtype: dict(str, dict(str, str)) """ @@ -83,7 +79,6 @@ class AdditionalPropertiesClass(object): """ Sets the map_of_map_property of this AdditionalPropertiesClass. - :param map_of_map_property: The map_of_map_property of this AdditionalPropertiesClass. :type: dict(str, dict(str, str)) """ diff --git a/samples/client/petstore/python/petstore_api/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py index c504d8d2cf7..c12c9d22284 100644 --- a/samples/client/petstore/python/petstore_api/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -43,13 +43,11 @@ class Animal(object): self._class_name = class_name self._color = color - @property def class_name(self): """ Gets the class_name of this Animal. - :return: The class_name of this Animal. :rtype: str """ @@ -60,7 +58,6 @@ class Animal(object): """ Sets the class_name of this Animal. - :param class_name: The class_name of this Animal. :type: str """ @@ -74,7 +71,6 @@ class Animal(object): """ Gets the color of this Animal. - :return: The color of this Animal. :rtype: str """ @@ -85,7 +81,6 @@ class Animal(object): """ Sets the color of this Animal. - :param color: The color of this Animal. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/api_response.py b/samples/client/petstore/python/petstore_api/models/api_response.py index e21f346c2d5..652c48b69b4 100644 --- a/samples/client/petstore/python/petstore_api/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -46,13 +46,11 @@ class ApiResponse(object): self._type = type self._message = message - @property def code(self): """ Gets the code of this ApiResponse. - :return: The code of this ApiResponse. :rtype: int """ @@ -63,7 +61,6 @@ class ApiResponse(object): """ Sets the code of this ApiResponse. - :param code: The code of this ApiResponse. :type: int """ @@ -75,7 +72,6 @@ class ApiResponse(object): """ Gets the type of this ApiResponse. - :return: The type of this ApiResponse. :rtype: str """ @@ -86,7 +82,6 @@ class ApiResponse(object): """ Sets the type of this ApiResponse. - :param type: The type of this ApiResponse. :type: str """ @@ -98,7 +93,6 @@ class ApiResponse(object): """ Gets the message of this ApiResponse. - :return: The message of this ApiResponse. :rtype: str """ @@ -109,7 +103,6 @@ class ApiResponse(object): """ Sets the message of this ApiResponse. - :param message: The message of this ApiResponse. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py index fad4b2b002d..64a9a2c0513 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py @@ -40,13 +40,11 @@ class ArrayOfArrayOfNumberOnly(object): self._array_array_number = array_array_number - @property def array_array_number(self): """ Gets the array_array_number of this ArrayOfArrayOfNumberOnly. - :return: The array_array_number of this ArrayOfArrayOfNumberOnly. :rtype: list[list[float]] """ @@ -57,7 +55,6 @@ class ArrayOfArrayOfNumberOnly(object): """ Sets the array_array_number of this ArrayOfArrayOfNumberOnly. - :param array_array_number: The array_array_number of this ArrayOfArrayOfNumberOnly. :type: list[list[float]] """ diff --git a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py index 04e9ae0289b..931ae9b1229 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py @@ -40,13 +40,11 @@ class ArrayOfNumberOnly(object): self._array_number = array_number - @property def array_number(self): """ Gets the array_number of this ArrayOfNumberOnly. - :return: The array_number of this ArrayOfNumberOnly. :rtype: list[float] """ @@ -57,7 +55,6 @@ class ArrayOfNumberOnly(object): """ Sets the array_number of this ArrayOfNumberOnly. - :param array_number: The array_number of this ArrayOfNumberOnly. :type: list[float] """ diff --git a/samples/client/petstore/python/petstore_api/models/array_test.py b/samples/client/petstore/python/petstore_api/models/array_test.py index 8394630b7a7..36bceca687f 100644 --- a/samples/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -46,13 +46,11 @@ class ArrayTest(object): self._array_array_of_integer = array_array_of_integer self._array_array_of_model = array_array_of_model - @property def array_of_string(self): """ Gets the array_of_string of this ArrayTest. - :return: The array_of_string of this ArrayTest. :rtype: list[str] """ @@ -63,7 +61,6 @@ class ArrayTest(object): """ Sets the array_of_string of this ArrayTest. - :param array_of_string: The array_of_string of this ArrayTest. :type: list[str] """ @@ -75,7 +72,6 @@ class ArrayTest(object): """ Gets the array_array_of_integer of this ArrayTest. - :return: The array_array_of_integer of this ArrayTest. :rtype: list[list[int]] """ @@ -86,7 +82,6 @@ class ArrayTest(object): """ Sets the array_array_of_integer of this ArrayTest. - :param array_array_of_integer: The array_array_of_integer of this ArrayTest. :type: list[list[int]] """ @@ -98,7 +93,6 @@ class ArrayTest(object): """ Gets the array_array_of_model of this ArrayTest. - :return: The array_array_of_model of this ArrayTest. :rtype: list[list[ReadOnlyFirst]] """ @@ -109,7 +103,6 @@ class ArrayTest(object): """ Sets the array_array_of_model of this ArrayTest. - :param array_array_of_model: The array_array_of_model of this ArrayTest. :type: list[list[ReadOnlyFirst]] """ diff --git a/samples/client/petstore/python/petstore_api/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py index 02e0c91680c..c52594a9870 100644 --- a/samples/client/petstore/python/petstore_api/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -46,13 +46,11 @@ class Cat(object): self._color = color self._declawed = declawed - @property def class_name(self): """ Gets the class_name of this Cat. - :return: The class_name of this Cat. :rtype: str """ @@ -63,7 +61,6 @@ class Cat(object): """ Sets the class_name of this Cat. - :param class_name: The class_name of this Cat. :type: str """ @@ -77,7 +74,6 @@ class Cat(object): """ Gets the color of this Cat. - :return: The color of this Cat. :rtype: str """ @@ -88,7 +84,6 @@ class Cat(object): """ Sets the color of this Cat. - :param color: The color of this Cat. :type: str """ @@ -100,7 +95,6 @@ class Cat(object): """ Gets the declawed of this Cat. - :return: The declawed of this Cat. :rtype: bool """ @@ -111,7 +105,6 @@ class Cat(object): """ Sets the declawed of this Cat. - :param declawed: The declawed of this Cat. :type: bool """ diff --git a/samples/client/petstore/python/petstore_api/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py index 595f29747fb..8a312c27094 100644 --- a/samples/client/petstore/python/petstore_api/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -43,13 +43,11 @@ class Category(object): self._id = id self._name = name - @property def id(self): """ Gets the id of this Category. - :return: The id of this Category. :rtype: int """ @@ -60,7 +58,6 @@ class Category(object): """ Sets the id of this Category. - :param id: The id of this Category. :type: int """ @@ -72,7 +69,6 @@ class Category(object): """ Gets the name of this Category. - :return: The name of this Category. :rtype: str """ @@ -83,7 +79,6 @@ class Category(object): """ Sets the name of this Category. - :param name: The name of this Category. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/client.py b/samples/client/petstore/python/petstore_api/models/client.py index 1c1b940f01f..47a89b35729 100644 --- a/samples/client/petstore/python/petstore_api/models/client.py +++ b/samples/client/petstore/python/petstore_api/models/client.py @@ -40,13 +40,11 @@ class Client(object): self._client = client - @property def client(self): """ Gets the client of this Client. - :return: The client of this Client. :rtype: str """ @@ -57,7 +55,6 @@ class Client(object): """ Sets the client of this Client. - :param client: The client of this Client. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py index c63e238a75c..0a13575dfb8 100644 --- a/samples/client/petstore/python/petstore_api/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -46,13 +46,11 @@ class Dog(object): self._color = color self._breed = breed - @property def class_name(self): """ Gets the class_name of this Dog. - :return: The class_name of this Dog. :rtype: str """ @@ -63,7 +61,6 @@ class Dog(object): """ Sets the class_name of this Dog. - :param class_name: The class_name of this Dog. :type: str """ @@ -77,7 +74,6 @@ class Dog(object): """ Gets the color of this Dog. - :return: The color of this Dog. :rtype: str """ @@ -88,7 +84,6 @@ class Dog(object): """ Sets the color of this Dog. - :param color: The color of this Dog. :type: str """ @@ -100,7 +95,6 @@ class Dog(object): """ Gets the breed of this Dog. - :return: The breed of this Dog. :rtype: str """ @@ -111,7 +105,6 @@ class Dog(object): """ Sets the breed of this Dog. - :param breed: The breed of this Dog. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/client/petstore/python/petstore_api/models/enum_arrays.py index 8e4bc507f87..a9c96ef1bff 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/models/enum_arrays.py @@ -43,13 +43,11 @@ class EnumArrays(object): self._just_symbol = just_symbol self._array_enum = array_enum - @property def just_symbol(self): """ Gets the just_symbol of this EnumArrays. - :return: The just_symbol of this EnumArrays. :rtype: str """ @@ -60,7 +58,6 @@ class EnumArrays(object): """ Sets the just_symbol of this EnumArrays. - :param just_symbol: The just_symbol of this EnumArrays. :type: str """ @@ -78,7 +75,6 @@ class EnumArrays(object): """ Gets the array_enum of this EnumArrays. - :return: The array_enum of this EnumArrays. :rtype: list[str] """ @@ -89,7 +85,6 @@ class EnumArrays(object): """ Sets the array_enum of this EnumArrays. - :param array_enum: The array_enum of this EnumArrays. :type: list[str] """ diff --git a/samples/client/petstore/python/petstore_api/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py index 749afd769b6..2769128794a 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -21,7 +21,7 @@ class EnumTest(object): NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ - def __init__(self, enum_string=None, enum_integer=None, enum_number=None): + def __init__(self, enum_string=None, enum_integer=None, enum_number=None, outer_enum=None): """ EnumTest - a model defined in Swagger @@ -33,26 +33,27 @@ class EnumTest(object): self.swagger_types = { 'enum_string': 'str', 'enum_integer': 'int', - 'enum_number': 'float' + 'enum_number': 'float', + 'outer_enum': 'OuterEnum' } self.attribute_map = { 'enum_string': 'enum_string', 'enum_integer': 'enum_integer', - 'enum_number': 'enum_number' + 'enum_number': 'enum_number', + 'outer_enum': 'outerEnum' } self._enum_string = enum_string self._enum_integer = enum_integer self._enum_number = enum_number - + self._outer_enum = outer_enum @property def enum_string(self): """ Gets the enum_string of this EnumTest. - :return: The enum_string of this EnumTest. :rtype: str """ @@ -63,7 +64,6 @@ class EnumTest(object): """ Sets the enum_string of this EnumTest. - :param enum_string: The enum_string of this EnumTest. :type: str """ @@ -81,7 +81,6 @@ class EnumTest(object): """ Gets the enum_integer of this EnumTest. - :return: The enum_integer of this EnumTest. :rtype: int """ @@ -92,7 +91,6 @@ class EnumTest(object): """ Sets the enum_integer of this EnumTest. - :param enum_integer: The enum_integer of this EnumTest. :type: int """ @@ -110,7 +108,6 @@ class EnumTest(object): """ Gets the enum_number of this EnumTest. - :return: The enum_number of this EnumTest. :rtype: float """ @@ -121,7 +118,6 @@ class EnumTest(object): """ Sets the enum_number of this EnumTest. - :param enum_number: The enum_number of this EnumTest. :type: float """ @@ -134,6 +130,27 @@ class EnumTest(object): self._enum_number = enum_number + @property + def outer_enum(self): + """ + Gets the outer_enum of this EnumTest. + + :return: The outer_enum of this EnumTest. + :rtype: OuterEnum + """ + return self._outer_enum + + @outer_enum.setter + def outer_enum(self, outer_enum): + """ + Sets the outer_enum of this EnumTest. + + :param outer_enum: The outer_enum of this EnumTest. + :type: OuterEnum + """ + + self._outer_enum = outer_enum + def to_dict(self): """ Returns the model properties as a dict diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index f5e5ea7e9ac..dcefc1e036b 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -76,13 +76,11 @@ class FormatTest(object): self._uuid = uuid self._password = password - @property def integer(self): """ Gets the integer of this FormatTest. - :return: The integer of this FormatTest. :rtype: int """ @@ -93,7 +91,6 @@ class FormatTest(object): """ Sets the integer of this FormatTest. - :param integer: The integer of this FormatTest. :type: int """ @@ -109,7 +106,6 @@ class FormatTest(object): """ Gets the int32 of this FormatTest. - :return: The int32 of this FormatTest. :rtype: int """ @@ -120,7 +116,6 @@ class FormatTest(object): """ Sets the int32 of this FormatTest. - :param int32: The int32 of this FormatTest. :type: int """ @@ -136,7 +131,6 @@ class FormatTest(object): """ Gets the int64 of this FormatTest. - :return: The int64 of this FormatTest. :rtype: int """ @@ -147,7 +141,6 @@ class FormatTest(object): """ Sets the int64 of this FormatTest. - :param int64: The int64 of this FormatTest. :type: int """ @@ -159,7 +152,6 @@ class FormatTest(object): """ Gets the number of this FormatTest. - :return: The number of this FormatTest. :rtype: float """ @@ -170,7 +162,6 @@ class FormatTest(object): """ Sets the number of this FormatTest. - :param number: The number of this FormatTest. :type: float """ @@ -188,7 +179,6 @@ class FormatTest(object): """ Gets the float of this FormatTest. - :return: The float of this FormatTest. :rtype: float """ @@ -199,7 +189,6 @@ class FormatTest(object): """ Sets the float of this FormatTest. - :param float: The float of this FormatTest. :type: float """ @@ -215,7 +204,6 @@ class FormatTest(object): """ Gets the double of this FormatTest. - :return: The double of this FormatTest. :rtype: float """ @@ -226,7 +214,6 @@ class FormatTest(object): """ Sets the double of this FormatTest. - :param double: The double of this FormatTest. :type: float """ @@ -242,7 +229,6 @@ class FormatTest(object): """ Gets the string of this FormatTest. - :return: The string of this FormatTest. :rtype: str """ @@ -253,7 +239,6 @@ class FormatTest(object): """ Sets the string of this FormatTest. - :param string: The string of this FormatTest. :type: str """ @@ -267,7 +252,6 @@ class FormatTest(object): """ Gets the byte of this FormatTest. - :return: The byte of this FormatTest. :rtype: str """ @@ -278,7 +262,6 @@ class FormatTest(object): """ Sets the byte of this FormatTest. - :param byte: The byte of this FormatTest. :type: str """ @@ -292,7 +275,6 @@ class FormatTest(object): """ Gets the binary of this FormatTest. - :return: The binary of this FormatTest. :rtype: str """ @@ -303,7 +285,6 @@ class FormatTest(object): """ Sets the binary of this FormatTest. - :param binary: The binary of this FormatTest. :type: str """ @@ -315,7 +296,6 @@ class FormatTest(object): """ Gets the date of this FormatTest. - :return: The date of this FormatTest. :rtype: date """ @@ -326,7 +306,6 @@ class FormatTest(object): """ Sets the date of this FormatTest. - :param date: The date of this FormatTest. :type: date """ @@ -340,7 +319,6 @@ class FormatTest(object): """ Gets the date_time of this FormatTest. - :return: The date_time of this FormatTest. :rtype: datetime """ @@ -351,7 +329,6 @@ class FormatTest(object): """ Sets the date_time of this FormatTest. - :param date_time: The date_time of this FormatTest. :type: datetime """ @@ -363,7 +340,6 @@ class FormatTest(object): """ Gets the uuid of this FormatTest. - :return: The uuid of this FormatTest. :rtype: str """ @@ -374,7 +350,6 @@ class FormatTest(object): """ Sets the uuid of this FormatTest. - :param uuid: The uuid of this FormatTest. :type: str """ @@ -386,7 +361,6 @@ class FormatTest(object): """ Gets the password of this FormatTest. - :return: The password of this FormatTest. :rtype: str """ @@ -397,7 +371,6 @@ class FormatTest(object): """ Sets the password of this FormatTest. - :param password: The password of this FormatTest. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py index 8a8b51e43d8..fcad8f02d4b 100644 --- a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py @@ -43,13 +43,11 @@ class HasOnlyReadOnly(object): self._bar = bar self._foo = foo - @property def bar(self): """ Gets the bar of this HasOnlyReadOnly. - :return: The bar of this HasOnlyReadOnly. :rtype: str """ @@ -60,7 +58,6 @@ class HasOnlyReadOnly(object): """ Sets the bar of this HasOnlyReadOnly. - :param bar: The bar of this HasOnlyReadOnly. :type: str """ @@ -72,7 +69,6 @@ class HasOnlyReadOnly(object): """ Gets the foo of this HasOnlyReadOnly. - :return: The foo of this HasOnlyReadOnly. :rtype: str """ @@ -83,7 +79,6 @@ class HasOnlyReadOnly(object): """ Sets the foo of this HasOnlyReadOnly. - :param foo: The foo of this HasOnlyReadOnly. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/list.py b/samples/client/petstore/python/petstore_api/models/list.py index 2c5797fe468..5e23577f213 100644 --- a/samples/client/petstore/python/petstore_api/models/list.py +++ b/samples/client/petstore/python/petstore_api/models/list.py @@ -40,13 +40,11 @@ class List(object): self.__123_list = _123_list - @property def _123_list(self): """ Gets the _123_list of this List. - :return: The _123_list of this List. :rtype: str """ @@ -57,7 +55,6 @@ class List(object): """ Sets the _123_list of this List. - :param _123_list: The _123_list of this List. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index 02c2d98c73a..61f97136063 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -43,13 +43,11 @@ class MapTest(object): self._map_map_of_string = map_map_of_string self._map_of_enum_string = map_of_enum_string - @property def map_map_of_string(self): """ Gets the map_map_of_string of this MapTest. - :return: The map_map_of_string of this MapTest. :rtype: dict(str, dict(str, str)) """ @@ -60,7 +58,6 @@ class MapTest(object): """ Sets the map_map_of_string of this MapTest. - :param map_map_of_string: The map_map_of_string of this MapTest. :type: dict(str, dict(str, str)) """ @@ -72,7 +69,6 @@ class MapTest(object): """ Gets the map_of_enum_string of this MapTest. - :return: The map_of_enum_string of this MapTest. :rtype: dict(str, str) """ @@ -83,7 +79,6 @@ class MapTest(object): """ Sets the map_of_enum_string of this MapTest. - :param map_of_enum_string: The map_of_enum_string of this MapTest. :type: dict(str, str) """ diff --git a/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py index 80ce3f32e6a..bdfa6721fb7 100644 --- a/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -46,13 +46,11 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): self._date_time = date_time self._map = map - @property def uuid(self): """ Gets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. - :return: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. :rtype: str """ @@ -63,7 +61,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Sets the uuid of this MixedPropertiesAndAdditionalPropertiesClass. - :param uuid: The uuid of this MixedPropertiesAndAdditionalPropertiesClass. :type: str """ @@ -75,7 +72,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Gets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. - :return: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. :rtype: datetime """ @@ -86,7 +82,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Sets the date_time of this MixedPropertiesAndAdditionalPropertiesClass. - :param date_time: The date_time of this MixedPropertiesAndAdditionalPropertiesClass. :type: datetime """ @@ -98,7 +93,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Gets the map of this MixedPropertiesAndAdditionalPropertiesClass. - :return: The map of this MixedPropertiesAndAdditionalPropertiesClass. :rtype: dict(str, Animal) """ @@ -109,7 +103,6 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Sets the map of this MixedPropertiesAndAdditionalPropertiesClass. - :param map: The map of this MixedPropertiesAndAdditionalPropertiesClass. :type: dict(str, Animal) """ diff --git a/samples/client/petstore/python/petstore_api/models/model_200_response.py b/samples/client/petstore/python/petstore_api/models/model_200_response.py index e835cefdf74..ea332d78a59 100644 --- a/samples/client/petstore/python/petstore_api/models/model_200_response.py +++ b/samples/client/petstore/python/petstore_api/models/model_200_response.py @@ -43,13 +43,11 @@ class Model200Response(object): self._name = name self.__class = _class - @property def name(self): """ Gets the name of this Model200Response. - :return: The name of this Model200Response. :rtype: int """ @@ -60,7 +58,6 @@ class Model200Response(object): """ Sets the name of this Model200Response. - :param name: The name of this Model200Response. :type: int """ @@ -72,7 +69,6 @@ class Model200Response(object): """ Gets the _class of this Model200Response. - :return: The _class of this Model200Response. :rtype: str """ @@ -83,7 +79,6 @@ class Model200Response(object): """ Sets the _class of this Model200Response. - :param _class: The _class of this Model200Response. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/model_return.py b/samples/client/petstore/python/petstore_api/models/model_return.py index d09930d164a..472c733793a 100644 --- a/samples/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -40,13 +40,11 @@ class ModelReturn(object): self.__return = _return - @property def _return(self): """ Gets the _return of this ModelReturn. - :return: The _return of this ModelReturn. :rtype: int """ @@ -57,7 +55,6 @@ class ModelReturn(object): """ Sets the _return of this ModelReturn. - :param _return: The _return of this ModelReturn. :type: int """ diff --git a/samples/client/petstore/python/petstore_api/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py index f6f8dcf9d78..f2ea96a04fe 100644 --- a/samples/client/petstore/python/petstore_api/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -49,13 +49,11 @@ class Name(object): self.__property = _property self.__123_number = _123_number - @property def name(self): """ Gets the name of this Name. - :return: The name of this Name. :rtype: int """ @@ -66,7 +64,6 @@ class Name(object): """ Sets the name of this Name. - :param name: The name of this Name. :type: int """ @@ -80,7 +77,6 @@ class Name(object): """ Gets the snake_case of this Name. - :return: The snake_case of this Name. :rtype: int """ @@ -91,7 +87,6 @@ class Name(object): """ Sets the snake_case of this Name. - :param snake_case: The snake_case of this Name. :type: int """ @@ -103,7 +98,6 @@ class Name(object): """ Gets the _property of this Name. - :return: The _property of this Name. :rtype: str """ @@ -114,7 +108,6 @@ class Name(object): """ Sets the _property of this Name. - :param _property: The _property of this Name. :type: str """ @@ -126,7 +119,6 @@ class Name(object): """ Gets the _123_number of this Name. - :return: The _123_number of this Name. :rtype: int """ @@ -137,7 +129,6 @@ class Name(object): """ Sets the _123_number of this Name. - :param _123_number: The _123_number of this Name. :type: int """ diff --git a/samples/client/petstore/python/petstore_api/models/number_only.py b/samples/client/petstore/python/petstore_api/models/number_only.py index b5d46279a6b..7b471e980d2 100644 --- a/samples/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/client/petstore/python/petstore_api/models/number_only.py @@ -40,13 +40,11 @@ class NumberOnly(object): self._just_number = just_number - @property def just_number(self): """ Gets the just_number of this NumberOnly. - :return: The just_number of this NumberOnly. :rtype: float """ @@ -57,7 +55,6 @@ class NumberOnly(object): """ Sets the just_number of this NumberOnly. - :param just_number: The just_number of this NumberOnly. :type: float """ diff --git a/samples/client/petstore/python/petstore_api/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py index fc1575308a6..fa8c7b8c750 100644 --- a/samples/client/petstore/python/petstore_api/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -55,13 +55,11 @@ class Order(object): self._status = status self._complete = complete - @property def id(self): """ Gets the id of this Order. - :return: The id of this Order. :rtype: int """ @@ -72,7 +70,6 @@ class Order(object): """ Sets the id of this Order. - :param id: The id of this Order. :type: int """ @@ -84,7 +81,6 @@ class Order(object): """ Gets the pet_id of this Order. - :return: The pet_id of this Order. :rtype: int """ @@ -95,7 +91,6 @@ class Order(object): """ Sets the pet_id of this Order. - :param pet_id: The pet_id of this Order. :type: int """ @@ -107,7 +102,6 @@ class Order(object): """ Gets the quantity of this Order. - :return: The quantity of this Order. :rtype: int """ @@ -118,7 +112,6 @@ class Order(object): """ Sets the quantity of this Order. - :param quantity: The quantity of this Order. :type: int """ @@ -130,7 +123,6 @@ class Order(object): """ Gets the ship_date of this Order. - :return: The ship_date of this Order. :rtype: datetime """ @@ -141,7 +133,6 @@ class Order(object): """ Sets the ship_date of this Order. - :param ship_date: The ship_date of this Order. :type: datetime """ @@ -182,7 +173,6 @@ class Order(object): """ Gets the complete of this Order. - :return: The complete of this Order. :rtype: bool """ @@ -193,7 +183,6 @@ class Order(object): """ Sets the complete of this Order. - :param complete: The complete of this Order. :type: bool """ diff --git a/samples/client/petstore/python/petstore_api/models/outer_enum.py b/samples/client/petstore/python/petstore_api/models/outer_enum.py new file mode 100644 index 00000000000..d86b2a3c03f --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/outer_enum.py @@ -0,0 +1,90 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from pprint import pformat +from six import iteritems +import re + + +class OuterEnum(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self): + """ + OuterEnum - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + + } + + self.attribute_map = { + + } + + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index 24f2390fde4..11f84a0f609 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -55,13 +55,11 @@ class Pet(object): self._tags = tags self._status = status - @property def id(self): """ Gets the id of this Pet. - :return: The id of this Pet. :rtype: int """ @@ -72,7 +70,6 @@ class Pet(object): """ Sets the id of this Pet. - :param id: The id of this Pet. :type: int """ @@ -84,7 +81,6 @@ class Pet(object): """ Gets the category of this Pet. - :return: The category of this Pet. :rtype: Category """ @@ -95,7 +91,6 @@ class Pet(object): """ Sets the category of this Pet. - :param category: The category of this Pet. :type: Category """ @@ -107,7 +102,6 @@ class Pet(object): """ Gets the name of this Pet. - :return: The name of this Pet. :rtype: str """ @@ -118,7 +112,6 @@ class Pet(object): """ Sets the name of this Pet. - :param name: The name of this Pet. :type: str """ @@ -132,7 +125,6 @@ class Pet(object): """ Gets the photo_urls of this Pet. - :return: The photo_urls of this Pet. :rtype: list[str] """ @@ -143,7 +135,6 @@ class Pet(object): """ Sets the photo_urls of this Pet. - :param photo_urls: The photo_urls of this Pet. :type: list[str] """ @@ -157,7 +148,6 @@ class Pet(object): """ Gets the tags of this Pet. - :return: The tags of this Pet. :rtype: list[Tag] """ @@ -168,7 +158,6 @@ class Pet(object): """ Sets the tags of this Pet. - :param tags: The tags of this Pet. :type: list[Tag] """ diff --git a/samples/client/petstore/python/petstore_api/models/read_only_first.py b/samples/client/petstore/python/petstore_api/models/read_only_first.py index 781522bbdc2..4316ec0911f 100644 --- a/samples/client/petstore/python/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/models/read_only_first.py @@ -43,13 +43,11 @@ class ReadOnlyFirst(object): self._bar = bar self._baz = baz - @property def bar(self): """ Gets the bar of this ReadOnlyFirst. - :return: The bar of this ReadOnlyFirst. :rtype: str """ @@ -60,7 +58,6 @@ class ReadOnlyFirst(object): """ Sets the bar of this ReadOnlyFirst. - :param bar: The bar of this ReadOnlyFirst. :type: str """ @@ -72,7 +69,6 @@ class ReadOnlyFirst(object): """ Gets the baz of this ReadOnlyFirst. - :return: The baz of this ReadOnlyFirst. :rtype: str """ @@ -83,7 +79,6 @@ class ReadOnlyFirst(object): """ Sets the baz of this ReadOnlyFirst. - :param baz: The baz of this ReadOnlyFirst. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/special_model_name.py b/samples/client/petstore/python/petstore_api/models/special_model_name.py index 3db03b41c77..3a133e2534b 100644 --- a/samples/client/petstore/python/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/models/special_model_name.py @@ -40,13 +40,11 @@ class SpecialModelName(object): self._special_property_name = special_property_name - @property def special_property_name(self): """ Gets the special_property_name of this SpecialModelName. - :return: The special_property_name of this SpecialModelName. :rtype: int """ @@ -57,7 +55,6 @@ class SpecialModelName(object): """ Sets the special_property_name of this SpecialModelName. - :param special_property_name: The special_property_name of this SpecialModelName. :type: int """ diff --git a/samples/client/petstore/python/petstore_api/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py index 469a3218f88..e0067308f99 100644 --- a/samples/client/petstore/python/petstore_api/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -43,13 +43,11 @@ class Tag(object): self._id = id self._name = name - @property def id(self): """ Gets the id of this Tag. - :return: The id of this Tag. :rtype: int """ @@ -60,7 +58,6 @@ class Tag(object): """ Sets the id of this Tag. - :param id: The id of this Tag. :type: int """ @@ -72,7 +69,6 @@ class Tag(object): """ Gets the name of this Tag. - :return: The name of this Tag. :rtype: str """ @@ -83,7 +79,6 @@ class Tag(object): """ Sets the name of this Tag. - :param name: The name of this Tag. :type: str """ diff --git a/samples/client/petstore/python/petstore_api/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py index 6add6b5254f..3d84d068d12 100644 --- a/samples/client/petstore/python/petstore_api/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -61,13 +61,11 @@ class User(object): self._phone = phone self._user_status = user_status - @property def id(self): """ Gets the id of this User. - :return: The id of this User. :rtype: int """ @@ -78,7 +76,6 @@ class User(object): """ Sets the id of this User. - :param id: The id of this User. :type: int """ @@ -90,7 +87,6 @@ class User(object): """ Gets the username of this User. - :return: The username of this User. :rtype: str """ @@ -101,7 +97,6 @@ class User(object): """ Sets the username of this User. - :param username: The username of this User. :type: str """ @@ -113,7 +108,6 @@ class User(object): """ Gets the first_name of this User. - :return: The first_name of this User. :rtype: str """ @@ -124,7 +118,6 @@ class User(object): """ Sets the first_name of this User. - :param first_name: The first_name of this User. :type: str """ @@ -136,7 +129,6 @@ class User(object): """ Gets the last_name of this User. - :return: The last_name of this User. :rtype: str """ @@ -147,7 +139,6 @@ class User(object): """ Sets the last_name of this User. - :param last_name: The last_name of this User. :type: str """ @@ -159,7 +150,6 @@ class User(object): """ Gets the email of this User. - :return: The email of this User. :rtype: str """ @@ -170,7 +160,6 @@ class User(object): """ Sets the email of this User. - :param email: The email of this User. :type: str """ @@ -182,7 +171,6 @@ class User(object): """ Gets the password of this User. - :return: The password of this User. :rtype: str """ @@ -193,7 +181,6 @@ class User(object): """ Sets the password of this User. - :param password: The password of this User. :type: str """ @@ -205,7 +192,6 @@ class User(object): """ Gets the phone of this User. - :return: The phone of this User. :rtype: str """ @@ -216,7 +202,6 @@ class User(object): """ Sets the phone of this User. - :param phone: The phone of this User. :type: str """ diff --git a/samples/client/petstore/python/setup.py b/samples/client/petstore/python/setup.py index 562a2aaae12..70fc36e144d 100644 --- a/samples/client/petstore/python/setup.py +++ b/samples/client/petstore/python/setup.py @@ -16,7 +16,6 @@ from setuptools import setup, find_packages NAME = "petstore_api" VERSION = "1.0.0" - # To install the library, run the following # # python setup.py install @@ -40,4 +39,3 @@ setup( This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ """ ) - diff --git a/samples/client/petstore/python/test/test_outer_enum.py b/samples/client/petstore/python/test/test_outer_enum.py new file mode 100644 index 00000000000..75d8cf32a1e --- /dev/null +++ b/samples/client/petstore/python/test/test_outer_enum.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.outer_enum import OuterEnum + + +class TestOuterEnum(unittest.TestCase): + """ OuterEnum unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testOuterEnum(self): + """ + Test OuterEnum + """ + model = petstore_api.models.outer_enum.OuterEnum() + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/client/petstore/python/tests/test_map_test.py b/samples/client/petstore/python/tests/test_map_test.py index 3ed54f93d24..19903c4e630 100644 --- a/samples/client/petstore/python/tests/test_map_test.py +++ b/samples/client/petstore/python/tests/test_map_test.py @@ -16,7 +16,6 @@ import petstore_api class MapTestTests(unittest.TestCase): - def test_maptest_init(self): # # Test MapTest construction with valid values diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 613b665cf5f..57cb40f9596 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -39,7 +39,7 @@ class MockPoolManager(object): self._reqs.append((args, kwargs)) def request(self, *args, **kwargs): - self._tc.assertTrue(len(self._reqs)>0) + self._tc.assertTrue(len(self._reqs) > 0) r = self._reqs.pop(0) self._tc.maxDiff = None self._tc.assertEqual(r[0], args) @@ -169,7 +169,7 @@ class PetApiTests(unittest.TestCase): self.pet_api.add_pet(body=self.pet) def callback_function(data): - #fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + # fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) self.assertIsNotNone(data) self.assertEqual(self.pet.id, data.id) self.assertIsNotNone(data.category) @@ -193,7 +193,7 @@ class PetApiTests(unittest.TestCase): self.pet_api.add_pet(body=self.pet) def callback_function(data): - #fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id) + # fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id) self.assertIsNotNone(data) self.assertEqual(self.pet.id, data[0].id) self.assertIsNotNone(data[0].category) diff --git a/samples/client/petstore/python/tests/util.py b/samples/client/petstore/python/tests/util.py index 6aeea16f63e..e83ca37a942 100644 --- a/samples/client/petstore/python/tests/util.py +++ b/samples/client/petstore/python/tests/util.py @@ -1,5 +1,6 @@ import random + def id_gen(bits=32): """ Returns a n-bit randomly generated int """ return int(random.getrandbits(bits)) From 4e2c037e21f1d157ef28e9b42d14aca3b68c1e7f Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 23 Nov 2016 00:16:28 +0800 Subject: [PATCH 097/269] [Java] fix Java (Jersey1.x) test case (#4239) * fix java jersey 1 test case * fix test for java jersey2.x api client --- samples/client/petstore/java/feign/hello.txt | 1 + .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 52 +++++++++++++++++++ .../petstore/java/jersey1/docs/EnumTest.md | 1 + .../petstore/java/jersey1/docs/OuterEnum.md | 14 +++++ .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 52 +++++++++++++++++++ .../swagger/client/model/EnumValueTest.java | 2 +- .../java/jersey2-java8/docs/EnumTest.md | 1 + .../java/jersey2-java8/docs/OuterEnum.md | 14 +++++ .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 52 +++++++++++++++++++ .../petstore/java/jersey2/docs/EnumTest.md | 1 + .../petstore/java/jersey2/docs/OuterEnum.md | 14 +++++ .../client/petstore/java/jersey2/hello.txt | 1 + .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 52 +++++++++++++++++++ .../swagger/client/model/EnumValueTest.java | 2 +- .../java/okhttp-gson/docs/EnumTest.md | 1 + .../java/okhttp-gson/docs/OuterEnum.md | 14 +++++ .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 45 ++++++++++++++++ .../client/petstore/java/retrofit/hello.txt | 1 + .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 45 ++++++++++++++++ .../petstore/java/retrofit2/docs/EnumTest.md | 1 + .../petstore/java/retrofit2/docs/OuterEnum.md | 14 +++++ .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 45 ++++++++++++++++ .../java/retrofit2rx/docs/EnumTest.md | 1 + .../java/retrofit2rx/docs/OuterEnum.md | 14 +++++ .../io/swagger/client/model/EnumTest.java | 28 +++++++++- .../io/swagger/client/model/OuterEnum.java | 45 ++++++++++++++++ 33 files changed, 691 insertions(+), 18 deletions(-) create mode 100644 samples/client/petstore/java/feign/hello.txt create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/jersey1/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/jersey2-java8/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/jersey2/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/jersey2/hello.txt create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/retrofit/hello.txt create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/retrofit2/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/retrofit2rx/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/OuterEnum.java diff --git a/samples/client/petstore/java/feign/hello.txt b/samples/client/petstore/java/feign/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/feign/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index e3d10bee512..3c43e963b04 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -123,6 +124,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -177,6 +181,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -189,12 +211,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -206,6 +229,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d71d45686a8 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/jersey1/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/jersey1/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey1/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/jersey1/docs/OuterEnum.md b/samples/client/petstore/java/jersey1/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index e3d10bee512..3c43e963b04 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -123,6 +124,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -177,6 +181,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -189,12 +211,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -206,6 +229,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d71d45686a8 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java index 867c454bff6..906d64cb0e2 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -45,7 +45,7 @@ public class EnumValueTest { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); ObjectWriter ow = mapper.writer(); String json = ow.writeValueAsString(enumTest); - assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\"}"); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\",\"outerEnum\":null}"); // test deserialization (json => object) EnumTest fromString = mapper.readValue(json, EnumTest.class); diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/jersey2-java8/docs/OuterEnum.md b/samples/client/petstore/java/jersey2-java8/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index e3d10bee512..3c43e963b04 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -123,6 +124,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -177,6 +181,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -189,12 +211,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -206,6 +229,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d71d45686a8 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/jersey2/docs/EnumTest.md b/samples/client/petstore/java/jersey2/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/jersey2/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/jersey2/docs/OuterEnum.md b/samples/client/petstore/java/jersey2/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/jersey2/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index e3d10bee512..3c43e963b04 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -123,6 +124,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -177,6 +181,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -189,12 +211,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -206,6 +229,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d71d45686a8 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java index 867c454bff6..906d64cb0e2 100644 --- a/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java +++ b/samples/client/petstore/java/jersey2/src/test/java/io/swagger/client/model/EnumValueTest.java @@ -45,7 +45,7 @@ public class EnumValueTest { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); ObjectWriter ow = mapper.writer(); String json = ow.writeValueAsString(enumTest); - assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\"}"); + assertEquals(json, "{\"enum_string\":\"lower\",\"enum_integer\":\"1\",\"enum_number\":\"1.1\",\"outerEnum\":null}"); // test deserialization (json => object) EnumTest fromString = mapper.readValue(json, EnumTest.class); diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md b/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index 469d3698211..ec1873d9971 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -17,6 +17,7 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -98,6 +99,9 @@ public class EnumTest { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; + @SerializedName("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -152,6 +156,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -164,12 +186,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -181,6 +204,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d7f8ec33900 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,45 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/retrofit/hello.txt b/samples/client/petstore/java/retrofit/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/retrofit/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index 469d3698211..ec1873d9971 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -17,6 +17,7 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -98,6 +99,9 @@ public class EnumTest { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; + @SerializedName("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -152,6 +156,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -164,12 +186,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -181,6 +204,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d7f8ec33900 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,45 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/retrofit2/docs/EnumTest.md b/samples/client/petstore/java/retrofit2/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/retrofit2/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2/docs/OuterEnum.md b/samples/client/petstore/java/retrofit2/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index 469d3698211..ec1873d9971 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -17,6 +17,7 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -98,6 +99,9 @@ public class EnumTest { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; + @SerializedName("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -152,6 +156,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -164,12 +186,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -181,6 +204,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d7f8ec33900 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,45 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md index deb1951c552..1746ccb273e 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md @@ -7,6 +7,7 @@ Name | Type | Description | Notes **enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] **enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] **enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/java/retrofit2rx/docs/OuterEnum.md b/samples/client/petstore/java/retrofit2rx/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index 469d3698211..ec1873d9971 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -17,6 +17,7 @@ import java.util.Objects; import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; /** * EnumTest @@ -98,6 +99,9 @@ public class EnumTest { @SerializedName("enum_number") private EnumNumberEnum enumNumber = null; + @SerializedName("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -152,6 +156,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -164,12 +186,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -181,6 +204,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..d7f8ec33900 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,45 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; + + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } +} + From 6ebc2fc0513b893608db82c20a3002bf9b3069c6 Mon Sep 17 00:00:00 2001 From: menchauser Date: Tue, 22 Nov 2016 20:18:40 +0400 Subject: [PATCH 098/269] Fix support for 'class' properties in Java codegen (#4237) * Fix support for 'class' properties in Java codegen Currently Java codegen works successfully for property named 'class' but fails on '_class', '__class', etc, because of 'Object.getClass()' overloading. This fix is intended to avoid all Object method overloading cases. * Regenerated samples for Java petstore-security-test --- .../languages/AbstractJavaCodegen.java | 2 +- .../codegen/java/AbstractJavaCodegenTest.java | 7 + .../swagger/codegen/java/JavaModelTest.java | 25 +++ ...ith-fake-endpoints-models-for-testing.yaml | 7 +- .../java/okhttp-gson/.travis.yml | 12 -- .../java/okhttp-gson/LICENSE | 201 ------------------ .../java/okhttp-gson/docs/FakeApi.md | 24 +-- .../java/okhttp-gson/docs/ModelReturn.md | 2 +- .../java/okhttp-gson/gradlew.bat | 180 ++++++++-------- .../java/okhttp-gson/pom.xml | 7 +- .../java/io/swagger/client/ApiCallback.java | 22 +- .../java/io/swagger/client/ApiClient.java | 30 +-- .../java/io/swagger/client/ApiException.java | 22 +- .../java/io/swagger/client/ApiResponse.java | 22 +- .../java/io/swagger/client/Configuration.java | 22 +- .../src/main/java/io/swagger/client/JSON.java | 24 +-- .../src/main/java/io/swagger/client/Pair.java | 22 +- .../swagger/client/ProgressRequestBody.java | 22 +- .../swagger/client/ProgressResponseBody.java | 22 +- .../java/io/swagger/client/StringUtil.java | 22 +- .../java/io/swagger/client/api/FakeApi.java | 58 ++--- .../io/swagger/client/auth/ApiKeyAuth.java | 22 +- .../swagger/client/auth/Authentication.java | 22 +- .../io/swagger/client/auth/HttpBasicAuth.java | 22 +- .../java/io/swagger/client/auth/OAuth.java | 22 +- .../io/swagger/client/auth/OAuthFlow.java | 22 +- .../io/swagger/client/model/ModelReturn.java | 35 ++- .../io/swagger/client/model/ClassModel.java | 90 ++++++++ .../petstore/java/jersey1/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 90 ++++++++ .../java/jersey2-java8/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 90 ++++++++ .../petstore/java/jersey2/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 90 ++++++++ .../java/okhttp-gson/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 89 ++++++++ .../io/swagger/client/model/ClassModel.java | 89 ++++++++ .../java/retrofit2/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 89 ++++++++ .../java/retrofit2rx/docs/ClassModel.md | 10 + .../io/swagger/client/model/ClassModel.java | 89 ++++++++ 41 files changed, 1040 insertions(+), 636 deletions(-) delete mode 100644 samples/client/petstore-security-test/java/okhttp-gson/LICENSE create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/jersey1/docs/ClassModel.md create mode 100644 samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/jersey2-java8/docs/ClassModel.md create mode 100644 samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/jersey2/docs/ClassModel.md create mode 100644 samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/okhttp-gson/docs/ClassModel.md create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/retrofit2/docs/ClassModel.md create mode 100644 samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/retrofit2rx/docs/ClassModel.md create mode 100644 samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ClassModel.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 6e90afaf61a..4f11ea6fa38 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -361,7 +361,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // sanitize name name = sanitizeName(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - if ("class".equals(name.toLowerCase())) { + if (name.toLowerCase().matches("^_*class$")) { return "propertyClass"; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java index 61da755f146..ee037ef9b9c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/AbstractJavaCodegenTest.java @@ -32,4 +32,11 @@ public class AbstractJavaCodegenTest { Assert.assertEquals("__", fakeJavaCodegen.toEnumVarName("_,.", "String")); } + @Test + public void toVarNameShouldAvoidOverloadingGetClassMethod() throws Exception { + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("class")); + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("_class")); + Assert.assertEquals("propertyClass", fakeJavaCodegen.toVarName("__class")); + } + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 2805d4d63c2..82d1555ea78 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -522,4 +522,29 @@ public class JavaModelTest { Assert.assertEquals(cm.name, name); Assert.assertEquals(cm.classname, expectedName); } + + @DataProvider(name = "classProperties") + public static Object[][] classProperties() { + return new Object[][] { + {"class", "getPropertyClass", "setPropertyClass", "propertyClass"}, + {"_class", "getPropertyClass", "setPropertyClass", "propertyClass"}, + {"__class", "getPropertyClass", "setPropertyClass", "propertyClass"} + }; + } + + @Test(dataProvider = "classProperties", description = "handle 'class' properties") + public void classPropertyTest(String baseName, String getter, String setter, String name) { + final Model model = new ModelImpl() + .description("a sample model") + .property(baseName, new StringProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, baseName); + Assert.assertEquals(property.getter, getter); + Assert.assertEquals(property.setter, setter); + Assert.assertEquals(property.name, name); + } + } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index fb075fcb5e5..ea868cec98f 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -958,9 +958,14 @@ definitions: type: integer format: int32 class: - type: string + type: string xml: name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string Dog: allOf: - $ref: '#/definitions/Animal' diff --git a/samples/client/petstore-security-test/java/okhttp-gson/.travis.yml b/samples/client/petstore-security-test/java/okhttp-gson/.travis.yml index 33e79472abd..70cb81a67c2 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/.travis.yml +++ b/samples/client/petstore-security-test/java/okhttp-gson/.travis.yml @@ -1,18 +1,6 @@ # # Generated by: https://github.com/swagger-api/swagger-codegen.git # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# language: java jdk: - oraclejdk8 diff --git a/samples/client/petstore-security-test/java/okhttp-gson/LICENSE b/samples/client/petstore-security-test/java/okhttp-gson/LICENSE deleted file mode 100644 index 8dada3edaf5..00000000000 --- a/samples/client/petstore-security-test/java/okhttp-gson/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md index 5ba69509352..5fadd46078b 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore-security-test/java/okhttp-gson/docs/FakeApi.md @@ -1,17 +1,17 @@ # FakeApi -All URIs are relative to *https://petstore.swagger.io ' \" =end/v2 ' \" =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r* Method | HTTP request | Description ------------- | ------------- | ------------- -[**testCodeInjectEnd**](FakeApi.md#testCodeInjectEnd) | **PUT** /fake | To test code injection ' \" =end +[**testCodeInjectEndRnNR**](FakeApi.md#testCodeInjectEndRnNR) | **PUT** /fake | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - -# **testCodeInjectEnd** -> testCodeInjectEnd(testCodeInjectEnd) + +# **testCodeInjectEndRnNR** +> testCodeInjectEndRnNR(testCodeInjectEndRnNR) -To test code injection ' \" =end +To test code injection *_/ ' \" =end -- \\r\\n \\n \\r ### Example ```java @@ -21,11 +21,11 @@ To test code injection ' \" =end FakeApi apiInstance = new FakeApi(); -String testCodeInjectEnd = "testCodeInjectEnd_example"; // String | To test code injection ' \" =end +String testCodeInjectEndRnNR = "testCodeInjectEndRnNR_example"; // String | To test code injection *_/ ' \" =end -- \\r\\n \\n \\r try { - apiInstance.testCodeInjectEnd(testCodeInjectEnd); + apiInstance.testCodeInjectEndRnNR(testCodeInjectEndRnNR); } catch (ApiException e) { - System.err.println("Exception when calling FakeApi#testCodeInjectEnd"); + System.err.println("Exception when calling FakeApi#testCodeInjectEndRnNR"); e.printStackTrace(); } ``` @@ -34,7 +34,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **testCodeInjectEnd** | **String**| To test code injection ' \" =end | [optional] + **testCodeInjectEndRnNR** | **String**| To test code injection *_/ ' \" =end -- \\r\\n \\n \\r | [optional] ### Return type @@ -46,6 +46,6 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ ' =end - - **Accept**: application/json, */ ' =end + - **Content-Type**: application/json, *_/ ' =end -- + - **Accept**: application/json, *_/ ' =end -- diff --git a/samples/client/petstore-security-test/java/okhttp-gson/docs/ModelReturn.md b/samples/client/petstore-security-test/java/okhttp-gson/docs/ModelReturn.md index ebeb3dff22b..62640f380c1 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/docs/ModelReturn.md +++ b/samples/client/petstore-security-test/java/okhttp-gson/docs/ModelReturn.md @@ -4,7 +4,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**_return** | **Integer** | property description ' \" =end | [optional] +**_return** | **Integer** | property description *_/ ' \" =end -- \\r\\n \\n \\r | [optional] diff --git a/samples/client/petstore-security-test/java/okhttp-gson/gradlew.bat b/samples/client/petstore-security-test/java/okhttp-gson/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/gradlew.bat +++ b/samples/client/petstore-security-test/java/okhttp-gson/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml index 2fe4b9d3a5e..d6ce1873282 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml +++ b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml @@ -96,6 +96,11 @@ + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.4 +
    @@ -145,4 +150,4 @@ 4.12 UTF-8 - + \ No newline at end of file diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index a0266b14370..fba62c4ee90 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 5053b3a2d69..076c4c09a10 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ @@ -124,7 +112,7 @@ public class ApiClient { */ public static final String LENIENT_DATETIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; - private String basePath = "https://petstore.swagger.io ' \" =end/v2 ' \" =end"; + private String basePath = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r"; private boolean lenientOnJson = false; private boolean debugging = false; private Map defaultHeaderMap = new HashMap(); @@ -173,7 +161,7 @@ public class ApiClient { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); - authentications.put("api_key", new ApiKeyAuth("header", "api_key */ ' " =end")); + authentications.put("api_key", new ApiKeyAuth("header", "api_key */ ' " =end -- \r\n \n \r")); authentications.put("petstore_auth", new OAuth()); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); @@ -191,7 +179,7 @@ public class ApiClient { /** * Set base path * - * @param basePath Base path of the URL (e.g https://petstore.swagger.io ' \" =end/v2 ' \" =end + * @param basePath Base path of the URL (e.g https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r * @return An instance of OkHttpClient */ public ApiClient setBasePath(String basePath) { @@ -812,6 +800,7 @@ public class ApiClient { * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -1006,6 +995,7 @@ public class ApiClient { * @param returnType Return type * @param callback ApiCallback */ + @SuppressWarnings("unchecked") public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { call.enqueue(new Callback() { @Override diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 180c563bb0c..fde9789ad13 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index e8e0ff2288a..caace845ec2 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index 47704a76d0d..876cb734bcc 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index c308440a0e4..4ff3984453d 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ @@ -103,6 +91,7 @@ public class JSON { * @param returnType The type to deserialize into * @return The deserialized Java object */ + @SuppressWarnings("unchecked") public T deserialize(String body, Type returnType) { try { if (apiClient.isLenientOnJson()) { @@ -161,7 +150,6 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { * * @param json Json element * @param date Type - * @param typeOfSrc Type * @param context Json Serialization Context * @return Date * @throws JsonParseException if fail to parse diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index af072d9054c..6c3c635847d 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java index 62f2e44a2a9..deca0211de6 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java index 98142d6ff46..6c1d34ca164 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 0c56536ee45..b013889ee6f 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 12d32188f18..0d0407f94b3 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ @@ -64,8 +52,8 @@ public class FakeApi { this.apiClient = apiClient; } - /* Build call for testCodeInjectEnd */ - private com.squareup.okhttp.Call testCodeInjectEndCall(String testCodeInjectEnd, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + /* Build call for testCodeInjectEndRnNR */ + private com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; @@ -77,17 +65,17 @@ public class FakeApi { Map localVarHeaderParams = new HashMap(); Map localVarFormParams = new HashMap(); - if (testCodeInjectEnd != null) - localVarFormParams.put("test code inject */ ' " =end", testCodeInjectEnd); + if (testCodeInjectEndRnNR != null) + localVarFormParams.put("test code inject */ ' " =end -- \r\n \n \r", testCodeInjectEndRnNR); final String[] localVarAccepts = { - "application/json", "*/ ' =end" + "application/json", "*_/ ' =end -- " }; final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); final String[] localVarContentTypes = { - "application/json", "*/ ' =end" + "application/json", "*_/ ' =end -- " }; final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); localVarHeaderParams.put("Content-Type", localVarContentType); @@ -109,36 +97,36 @@ public class FakeApi { } /** - * To test code injection ' \" =end + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * - * @param testCodeInjectEnd To test code injection ' \" =end (optional) + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public void testCodeInjectEnd(String testCodeInjectEnd) throws ApiException { - testCodeInjectEndWithHttpInfo(testCodeInjectEnd); + public void testCodeInjectEndRnNR(String testCodeInjectEndRnNR) throws ApiException { + testCodeInjectEndRnNRWithHttpInfo(testCodeInjectEndRnNR); } /** - * To test code injection ' \" =end + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * - * @param testCodeInjectEnd To test code injection ' \" =end (optional) + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @return ApiResponse<Void> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ - public ApiResponse testCodeInjectEndWithHttpInfo(String testCodeInjectEnd) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, null, null); + public ApiResponse testCodeInjectEndRnNRWithHttpInfo(String testCodeInjectEndRnNR) throws ApiException { + com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, null, null); return apiClient.execute(call); } /** - * To test code injection ' \" =end (asynchronously) + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) * - * @param testCodeInjectEnd To test code injection ' \" =end (optional) + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ - public com.squareup.okhttp.Call testCodeInjectEndAsync(String testCodeInjectEnd, final ApiCallback callback) throws ApiException { + public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(String testCodeInjectEndRnNR, final ApiCallback callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; @@ -159,7 +147,7 @@ public class FakeApi { }; } - com.squareup.okhttp.Call call = testCodeInjectEndCall(testCodeInjectEnd, progressListener, progressRequestListener); + com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index e12f1535217..643d5523f05 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 5028528284a..3b116e7cf41 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 93818f3e1c8..893465d5f43 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index 13c6607378d..2a1e2a523ca 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java index d0d37d9a7c4..2a88e57bb6a 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java index e0c68ada635..7e26fef904c 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelReturn.java @@ -1,25 +1,13 @@ -/** - * Swagger Petstore ' \" =end - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end +/* + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ @@ -30,13 +18,12 @@ import com.google.gson.annotations.SerializedName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - /** - * Model for testing reserved words ' \" =end + * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r */ -@ApiModel(description = "Model for testing reserved words ' \" =end") +@ApiModel(description = "Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r") -public class ModelReturn { +public class ModelReturn { @SerializedName("return") private Integer _return = null; @@ -46,10 +33,10 @@ public class ModelReturn { } /** - * property description ' \" =end + * property description *_/ ' \" =end -- \\r\\n \\n \\r * @return _return **/ - @ApiModelProperty(example = "null", value = "property description ' \" =end") + @ApiModelProperty(example = "null", value = "property description *_/ ' \" =end -- \\r\\n \\n \\r") public Integer getReturn() { return _return; } @@ -76,6 +63,7 @@ public class ModelReturn { return Objects.hash(_return); } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -96,5 +84,6 @@ public class ModelReturn { } return o.toString().replace("\n", "\n "); } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..48bb3d85f06 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/docs/ClassModel.md b/samples/client/petstore/java/jersey1/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/jersey1/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..48bb3d85f06 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey2-java8/docs/ClassModel.md b/samples/client/petstore/java/jersey2-java8/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..48bb3d85f06 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey2/docs/ClassModel.md b/samples/client/petstore/java/jersey2/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/jersey2/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..48bb3d85f06 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/docs/ClassModel.md b/samples/client/petstore/java/okhttp-gson/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..ee9722ad373 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,89 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @SerializedName("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..ee9722ad373 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,89 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @SerializedName("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2/docs/ClassModel.md b/samples/client/petstore/java/retrofit2/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..ee9722ad373 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,89 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @SerializedName("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2rx/docs/ClassModel.md b/samples/client/petstore/java/retrofit2rx/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..ee9722ad373 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,89 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @SerializedName("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + From 932dc5fba553839064e16d8dea5605898200ea5f Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 23 Nov 2016 01:14:52 +0800 Subject: [PATCH 099/269] add [Riffyn](https://riffyn.com) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2af1980f877..fbb02a3033c 100644 --- a/README.md +++ b/README.md @@ -802,6 +802,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Reload! A/S](https://reload.dk/) - [REstore](https://www.restore.eu) - [Revault Sàrl](http://revault.ch) +- [Riffyn](https://riffyn.com) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [SCOOP Software GmbH](http://www.scoop-software.de) - [Skurt](http://www.skurt.com) From ba194ba361352be03f930cf8a06c3e9f1284a4d4 Mon Sep 17 00:00:00 2001 From: plankswert Date: Wed, 23 Nov 2016 01:31:31 -0500 Subject: [PATCH 100/269] Added support for string responses (#4057) * Added support for string responses When a method/URL/response is defined to return string: - If no content types are define, default to 'text/plain' instead of 'application/json' - Add response handler, that returns the reponse string as-is if response content-type is 'text/plain' * Removed use of unused tag vendor tag - The tag was vendorExtensions.x-codegen-response.isPrimitiveType --- .../resources/cpprest/api-source.mustache | 25 +++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache index 21c5eff5553..72a91ebc64a 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -53,7 +53,17 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + {{#vendorExtensions.x-codegen-response.isString}} + responseHttpContentType = U("text/plain"); + {{/vendorExtensions.x-codegen-response.isString}} + {{^vendorExtensions.x-codegen-response.isString}} + responseHttpContentType = U("application/json"); + {{/vendorExtensions.x-codegen-response.isString}} + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -62,6 +72,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { responseHttpContentType = U("multipart/form-data"); } + {{#vendorExtensions.x-codegen-response.isString}} + // plain text + else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) + { + responseHttpContentType = U("text/plain"); + } + {{/vendorExtensions.x-codegen-response.isString}} {{#vendorExtensions.x-codegen-response-ishttpcontent}} else { @@ -266,7 +283,11 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r {{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json); {{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); {{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}} - } + }{{#vendorExtensions.x-codegen-response.isString}} + else if(responseHttpContentType == U("text/plain")) + { + result = response; + }{{/vendorExtensions.x-codegen-response.isString}} // else if(responseHttpContentType == U("multipart/form-data")) // { // TODO multipart response parsing From 4c05d5f098d117bf5b5ee9e3edeef9d87efe9682 Mon Sep 17 00:00:00 2001 From: Nick Maynard Date: Wed, 23 Nov 2016 07:07:25 +0000 Subject: [PATCH 101/269] Allow Java source formatting mvn formatter:format (#4214) Uses Eclipse formatting tools with a configuration matching Google's style guide (plus our customisations). --- eclipse-formatter.xml | 341 +++++++++++++++++++ modules/swagger-codegen-cli/pom.xml | 8 + modules/swagger-codegen-maven-plugin/pom.xml | 10 + modules/swagger-codegen/pom.xml | 8 + modules/swagger-generator/pom.xml | 8 + pom.xml | 31 ++ 6 files changed, 406 insertions(+) create mode 100644 eclipse-formatter.xml diff --git a/eclipse-formatter.xml b/eclipse-formatter.xml new file mode 100644 index 00000000000..a2b5fd1e1f0 --- /dev/null +++ b/eclipse-formatter.xml @@ -0,0 +1,341 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 6b56d5a6f56..36482e0752b 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -61,6 +61,14 @@ + + net.revelc.code + formatter-maven-plugin + + + ${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml + + diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 4df64ca4e61..85ac4a99433 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -83,5 +83,15 @@ + + + net.revelc.code + formatter-maven-plugin + + + ${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml + + + diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 21e44ce2547..6288700712b 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -110,6 +110,14 @@ maven-release-plugin 2.5.3 + + net.revelc.code + formatter-maven-plugin + + + ${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml + + diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index c44e4c2afd0..c086715639f 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -119,6 +119,14 @@ + + net.revelc.code + formatter-maven-plugin + + + ${project.basedir}${file.separator}${project.parent.relativePath}${file.separator}eclipse-formatter.xml + + diff --git a/pom.xml b/pom.xml index 562011ff714..b85e4885cb9 100644 --- a/pom.xml +++ b/pom.xml @@ -67,6 +67,26 @@ target ${project.artifactId}-${project.version} + + net.revelc.code + formatter-maven-plugin + + + + 1.7 + 1.7 + 1.7 + LF + + org.apache.maven.plugins maven-checkstyle-plugin @@ -77,6 +97,8 @@ validate google_checkstyle.xml + + ${project.build.sourceDirectory} UTF-8 true true @@ -201,6 +223,15 @@ + + + + net.revelc.code + formatter-maven-plugin + 0.5.2 + + + From 2f80568658b0607b75aee103101bcdf6ce0fe794 Mon Sep 17 00:00:00 2001 From: Sreenidhi Sreesha Date: Tue, 22 Nov 2016 23:13:15 -0800 Subject: [PATCH 102/269] Refactor code to make it more readable. (#4224) --- .../io/swagger/codegen/DefaultCodegen.java | 117 +- .../io/swagger/codegen/DefaultGenerator.java | 1172 ++++++++--------- .../languages/AbstractJavaCodegen.java | 102 +- 3 files changed, 686 insertions(+), 705 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 2eac677995c..265513d7189 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -217,7 +217,6 @@ public class DefaultCodegen { // for enum model if (Boolean.TRUE.equals(cm.isEnum) && cm.allowableValues != null) { Map allowableValues = cm.allowableValues; - List values = (List) allowableValues.get("values"); List> enumVars = new ArrayList>(); String commonPrefix = findCommonPrefixOfVars(values); @@ -259,7 +258,6 @@ public class DefaultCodegen { public String findCommonPrefixOfVars(List vars) { try { String[] listStr = vars.toArray(new String[vars.size()]); - String prefix = StringUtils.getCommonPrefix(listStr); // exclude trailing characters that should be part of a valid variable // e.g. ["status-on", "status-off"] => "status-" (not "status-o") @@ -362,7 +360,13 @@ public class DefaultCodegen { // replace " with \" // outter unescape to retain the original multi-byte characters // finally escalate characters avoiding code injection - return escapeUnsafeCharacters(StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," ").replace("\\", "\\\\").replace("\"", "\\\"")); + return escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(input) + .replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]"," ") + .replace("\\", "\\\\") + .replace("\"", "\\\"")); } /** @@ -372,7 +376,8 @@ public class DefaultCodegen { * @return string with unsafe characters removed or escaped */ public String escapeUnsafeCharacters(String input) { - LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape unsafe characters"); + LOGGER.warn("escapeUnsafeCharacters should be overridden in the code generator with proper logic to escape " + + "unsafe characters"); // doing nothing by default and code generator should implement // the logic to prevent code injection // later we'll make this method abstract to make sure @@ -386,7 +391,8 @@ public class DefaultCodegen { * @return string with quotation mark removed or escaped */ public String escapeQuotationMark(String input) { - LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape single/double quote"); + LOGGER.warn("escapeQuotationMark should be overridden in the code generator with proper logic to escape " + + "single/double quote"); return input.replace("\"", "\\\""); } @@ -1232,7 +1238,6 @@ public class DefaultCodegen { m.discriminator = ((ModelImpl) model).getDiscriminator(); } - if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); @@ -1319,7 +1324,7 @@ public class DefaultCodegen { addVars(m, properties, required, allProperties, allRequired); } else { ModelImpl impl = (ModelImpl) model; - if (m != null && impl.getType() != null) { + if (impl.getType() != null) { Property p = PropertyBuilder.build(impl.getType(), impl.getFormat(), null); m.dataType = getSwaggerType(p); } @@ -1350,7 +1355,7 @@ public class DefaultCodegen { if (model == null || allDefinitions == null) return false; - Model child = ((ComposedModel) model).getChild(); + Model child = model.getChild(); if (child instanceof ModelImpl && ((ModelImpl) child).getDiscriminator() != null) { return true; } @@ -1372,7 +1377,9 @@ public class DefaultCodegen { addParentContainer(codegenModel, codegenModel.name, mapProperty); } - protected void addProperties(Map properties, List required, Model model, Map allDefinitions) { + protected void addProperties(Map properties, + List required, Model model, + Map allDefinitions) { if (model instanceof ModelImpl) { ModelImpl mi = (ModelImpl) model; @@ -1403,9 +1410,7 @@ public class DefaultCodegen { if (name == null || name.length() == 0) { return name; } - return camelize(toVarName(name)); - } /** @@ -1422,7 +1427,6 @@ public class DefaultCodegen { } CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); - property.name = toVarName(name); property.baseName = name; property.nameInCamelCase = camelize(property.name, false); @@ -1504,7 +1508,6 @@ public class DefaultCodegen { property.allowableValues = allowableValues; }*/ } - if (p instanceof IntegerProperty) { IntegerProperty sp = (IntegerProperty) p; property.isInteger = true; @@ -1522,7 +1525,6 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if (p instanceof LongProperty) { LongProperty sp = (LongProperty) p; property.isLong = true; @@ -1540,11 +1542,9 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if (p instanceof BooleanProperty) { property.isBoolean = true; } - if (p instanceof BinaryProperty) { property.isBinary = true; } @@ -1554,7 +1554,6 @@ public class DefaultCodegen { if (p instanceof ByteArrayProperty) { property.isByteArray = true; } - // type is number and without format if (p instanceof DecimalProperty && !(p instanceof DoubleProperty) && !(p instanceof FloatProperty)) { DecimalProperty sp = (DecimalProperty) p; @@ -1573,7 +1572,6 @@ public class DefaultCodegen { property.allowableValues = allowableValues; }*/ } - if (p instanceof DoubleProperty) { DoubleProperty sp = (DoubleProperty) p; property.isDouble = true; @@ -1591,7 +1589,6 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if (p instanceof FloatProperty) { FloatProperty sp = (FloatProperty) p; property.isFloat = true; @@ -1627,7 +1624,6 @@ public class DefaultCodegen { property.allowableValues = allowableValues; } } - if (p instanceof DateTimeProperty) { DateTimeProperty sp = (DateTimeProperty) p; property.isDateTime = true; @@ -1690,25 +1686,26 @@ public class DefaultCodegen { protected void updatePropertyForArray(CodegenProperty property, CodegenProperty innerProperty) { if (innerProperty == null) { LOGGER.warn("skipping invalid array property " + Json.pretty(property)); - } else { - if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { - property.complexType = innerProperty.baseType; - } else { - property.isPrimitiveType = true; - } - property.items = innerProperty; - // inner item is Enum - if (isPropertyInnerMostEnum(property)) { - // isEnum is set to true when the type is an enum - // or the inner type of an array/map is an enum - property.isEnum = true; - // update datatypeWithEnum and default value for array - // e.g. List => List - updateDataTypeWithEnumForArray(property); - // set allowable values to enum values (including array/map of enum) - property.allowableValues = getInnerEnumAllowableValues(property); - } + return; } + if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { + property.complexType = innerProperty.baseType; + } else { + property.isPrimitiveType = true; + } + property.items = innerProperty; + // inner item is Enum + if (isPropertyInnerMostEnum(property)) { + // isEnum is set to true when the type is an enum + // or the inner type of an array/map is an enum + property.isEnum = true; + // update datatypeWithEnum and default value for array + // e.g. List => List + updateDataTypeWithEnumForArray(property); + // set allowable values to enum values (including array/map of enum) + property.allowableValues = getInnerEnumAllowableValues(property); + } + } /** @@ -1720,24 +1717,23 @@ public class DefaultCodegen { if (innerProperty == null) { LOGGER.warn("skipping invalid map property " + Json.pretty(property)); return; + } + if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { + property.complexType = innerProperty.baseType; } else { - if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { - property.complexType = innerProperty.baseType; - } else { - property.isPrimitiveType = true; - } - property.items = innerProperty; - // inner item is Enum - if (isPropertyInnerMostEnum(property)) { - // isEnum is set to true when the type is an enum - // or the inner type of an array/map is an enum - property.isEnum = true; - // update datatypeWithEnum and default value for map - // e.g. Dictionary => Dictionary - updateDataTypeWithEnumForMap(property); - // set allowable values to enum values (including array/map of enum) - property.allowableValues = getInnerEnumAllowableValues(property); - } + property.isPrimitiveType = true; + } + property.items = innerProperty; + // inner item is Enum + if (isPropertyInnerMostEnum(property)) { + // isEnum is set to true when the type is an enum + // or the inner type of an array/map is an enum + property.isEnum = true; + // update datatypeWithEnum and default value for map + // e.g. Dictionary => Dictionary + updateDataTypeWithEnumForMap(property); + // set allowable values to enum values (including array/map of enum) + property.allowableValues = getInnerEnumAllowableValues(property); } } @@ -1867,7 +1863,11 @@ public class DefaultCodegen { * @param swagger a Swagger object representing the spec * @return Codegen Operation object */ - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + public CodegenOperation fromOperation(String path, + String httpMethod, + Operation operation, + Map definitions, + Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -1936,7 +1936,7 @@ public class DefaultCodegen { } // if "produces" is defined (per operation or using global definition) - if (produces != null && produces.size() > 0) { + if (produces != null && !produces.isEmpty()) { List> c = new ArrayList>(); int count = 0; for (String key : produces) { @@ -2228,7 +2228,7 @@ public class DefaultCodegen { if (param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; - Property property = null; + Property property; String collectionFormat = null; String type = qp.getType(); if (null == type) { @@ -3345,7 +3345,6 @@ public class DefaultCodegen { if (pattern != null && !pattern.matches("^/.*")) { return "/" + pattern + "/"; } - return pattern; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 6d481148c54..b97c562a1a8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -20,79 +20,74 @@ import java.util.*; import org.apache.commons.lang3.StringUtils; public class DefaultGenerator extends AbstractGenerator implements Generator { - protected Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); - + protected final Logger LOGGER = LoggerFactory.getLogger(DefaultGenerator.class); protected CodegenConfig config; protected ClientOptInput opts; protected Swagger swagger; protected CodegenIgnoreProcessor ignoreProcessor; + private Boolean generateApis = null; + private Boolean generateModels = null; + private Boolean generateSupportingFiles = null; + private Boolean generateApiTests = null; + private Boolean generateApiDocumentation = null; + private Boolean generateModelTests = null; + private Boolean generateModelDocumentation = null; + private String basePath; + private String basePathWithoutHost; + private String contextPath; @Override public Generator opts(ClientOptInput opts) { this.opts = opts; - this.swagger = opts.getSwagger(); this.config = opts.getConfig(); - this.config.additionalProperties().putAll(opts.getOpts().getProperties()); - ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir()); - return this; } - @Override - public List generate() { - Boolean generateApis = null; - Boolean generateModels = null; - Boolean generateSupportingFiles = null; - Boolean generateApiTests = null; - Boolean generateApiDocumentation = null; - Boolean generateModelTests = null; - Boolean generateModelDocumentation = null; + private String getScheme() { + String scheme; + if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + scheme = config.escapeText(swagger.getSchemes().get(0).toValue()); + } else { + scheme = "https"; + } + scheme = config.escapeText(scheme); + return scheme; + } - Set modelsToGenerate = null; - Set apisToGenerate = null; - Set supportingFilesToGenerate = null; + private String getHost(){ + StringBuilder hostBuilder = new StringBuilder(); + hostBuilder.append(getScheme()); + hostBuilder.append("://"); + if (swagger.getHost() != null) { + hostBuilder.append(swagger.getHost()); + } else { + hostBuilder.append("localhost"); + } + if (swagger.getBasePath() != null) { + hostBuilder.append(swagger.getBasePath()); + } + return hostBuilder.toString(); + } + + private void configureGeneratorProperties() { // allows generating only models by specifying a CSV of models to generate, or empty for all - if(System.getProperty("models") != null) { - String modelNames = System.getProperty("models"); - generateModels = true; - if(!modelNames.isEmpty()) { - modelsToGenerate = new HashSet(Arrays.asList(modelNames.split(","))); - } - } - if(System.getProperty("apis") != null) { - String apiNames = System.getProperty("apis"); - generateApis = true; - if(!apiNames.isEmpty()) { - apisToGenerate = new HashSet(Arrays.asList(apiNames.split(","))); - } - } - if(System.getProperty("supportingFiles") != null) { - String supportingFiles = System.getProperty("supportingFiles"); - generateSupportingFiles = true; - if(!supportingFiles.isEmpty()) { - supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); - } - } - if(System.getProperty("modelTests") != null) { - generateModelTests = Boolean.valueOf(System.getProperty("modelTests")); - } - if(System.getProperty("modelDocs") != null) { - generateModelDocumentation = Boolean.valueOf(System.getProperty("modelDocs")); - } - if(System.getProperty("apiTests") != null) { - generateApiTests = Boolean.valueOf(System.getProperty("apiTests")); - } - if(System.getProperty("apiDocs") != null) { - generateApiDocumentation = Boolean.valueOf(System.getProperty("apiDocs")); - } + generateApis = System.getProperty("apis") != null ? true:null; + generateModels = System.getProperty("models") != null ? true: null; + generateSupportingFiles = System.getProperty("supportingFiles") != null ? true:null; + // model/api tests and documentation options rely on parent generate options (api or model) and no other options. + // They default to true in all scenarios and can only be marked false explicitly + generateModelTests = System.getProperty("modelTests") != null ? Boolean.valueOf(System.getProperty("modelTests")): true; + generateModelDocumentation = System.getProperty("modelDocs") != null ? Boolean.valueOf(System.getProperty("modelDocs")):true; + generateApiTests = System.getProperty("apiTests") != null ? Boolean.valueOf(System.getProperty("apiTests")): true; + generateApiDocumentation = System.getProperty("apiDocs") != null ? Boolean.valueOf(System.getProperty("apiDocs")):true; if(generateApis == null && generateModels == null && generateSupportingFiles == null) { // no specifics are set, generate everything - generateApis = true; generateModels = true; generateSupportingFiles = true; + generateApis = generateModels = generateSupportingFiles = true; } else { if(generateApis == null) { @@ -105,267 +100,224 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { generateSupportingFiles = false; } } - - // model/api tests and documentation options rely on parent generate options (api or model) and no other options. - // They default to true in all scenarios and can only be marked false explicitly - if (generateModelTests == null) { - generateModelTests = true; - } - if (generateModelDocumentation == null) { - generateModelDocumentation = true; - } - if (generateApiTests == null) { - generateApiTests = true; - } - if (generateApiDocumentation == null) { - generateApiDocumentation = true; - } - // Additional properties added for tests to exclude references in project related files config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests); config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); - if(Boolean.FALSE.equals(generateApiTests) && Boolean.FALSE.equals(generateModelTests)) { - config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, Boolean.TRUE); - } - - if (swagger == null || config == null) { - throw new RuntimeException("missing swagger input or config!"); + if(!generateApiTests && !generateModelTests) { + config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true); } if (System.getProperty("debugSwagger") != null) { Json.prettyPrint(swagger); } - List files = new ArrayList(); config.processOpts(); config.preprocessSwagger(swagger); - config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatorClass", config.getClass().toString()); config.additionalProperties().put("inputSpec", config.getInputSpec()); - - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); - if (info.getTitle() != null) { - config.additionalProperties().put("appName", config.escapeText(info.getTitle())); - } - if (info.getVersion() != null) { - config.additionalProperties().put("appVersion", config.escapeText(info.getVersion())); - } - - if (StringUtils.isEmpty(info.getDescription())) { - // set a default description if none if provided - config.additionalProperties().put("appDescription", - "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); - } else { - config.additionalProperties().put("appDescription", - config.escapeText(info.getDescription())); - } - - if (info.getContact() != null) { - Contact contact = info.getContact(); - config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl())); - if (contact.getEmail() != null) { - config.additionalProperties().put("infoEmail", config.escapeText(contact.getEmail())); - } - } - if (info.getLicense() != null) { - License license = info.getLicense(); - if (license.getName() != null) { - config.additionalProperties().put("licenseInfo", config.escapeText(license.getName())); - } - if (license.getUrl() != null) { - config.additionalProperties().put("licenseUrl", config.escapeText(license.getUrl())); - } - } - if (info.getVersion() != null) { - config.additionalProperties().put("version", config.escapeText(info.getVersion())); - } - if (info.getTermsOfService() != null) { - config.additionalProperties().put("termsOfService", config.escapeText(info.getTermsOfService())); - } + if (swagger.getVendorExtensions() != null) { + config.vendorExtensions().putAll(swagger.getVendorExtensions()); } + } - if(swagger.getVendorExtensions() != null) { - config.vendorExtensions().putAll(swagger.getVendorExtensions()); + private void configureSwaggerInfo() { + Info info = swagger.getInfo(); + if (info == null) { + return; } - - StringBuilder hostBuilder = new StringBuilder(); - String scheme; - if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { - scheme = config.escapeText(swagger.getSchemes().get(0).toValue()); + if (info.getTitle() != null) { + config.additionalProperties().put("appName", config.escapeText(info.getTitle())); + } + if (info.getVersion() != null) { + config.additionalProperties().put("appVersion", config.escapeText(info.getVersion())); + } + if (StringUtils.isEmpty(info.getDescription())) { + // set a default description if none if provided + config.additionalProperties().put("appDescription", + "No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)"); } else { - scheme = "https"; + config.additionalProperties().put("appDescription", config.escapeText(info.getDescription())); } - scheme = config.escapeText(scheme); - hostBuilder.append(scheme); - hostBuilder.append("://"); - if (swagger.getHost() != null) { - hostBuilder.append(swagger.getHost()); - } else { - hostBuilder.append("localhost"); + + if (info.getContact() != null) { + Contact contact = info.getContact(); + config.additionalProperties().put("infoUrl", config.escapeText(contact.getUrl())); + if (contact.getEmail() != null) { + config.additionalProperties().put("infoEmail", config.escapeText(contact.getEmail())); + } } - if (swagger.getBasePath() != null) { - hostBuilder.append(swagger.getBasePath()); + if (info.getLicense() != null) { + License license = info.getLicense(); + if (license.getName() != null) { + config.additionalProperties().put("licenseInfo", config.escapeText(license.getName())); + } + if (license.getUrl() != null) { + config.additionalProperties().put("licenseUrl", config.escapeText(license.getUrl())); + } } - String contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath()); - String basePath = config.escapeText(hostBuilder.toString()); - String basePathWithoutHost = config.escapeText(swagger.getBasePath()); + if (info.getVersion() != null) { + config.additionalProperties().put("version", config.escapeText(info.getVersion())); + } + if (info.getTermsOfService() != null) { + config.additionalProperties().put("termsOfService", config.escapeText(info.getTermsOfService())); + } + } - // resolve inline models - InlineModelResolver inlineModelResolver = new InlineModelResolver(); - inlineModelResolver.flatten(swagger); + private void generateModelTests(List files, Map models, String modelName) throws IOException{ + // to generate model test files + for (String templateName : config.modelTestTemplateFiles().keySet()) { + String suffix = config.modelTestTemplateFiles().get(templateName); + String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(modelName) + suffix; + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); + continue; + } + File written = processTemplateToFile(models, templateName, filename); + if (written != null) { + files.add(written); + } + } + } - List allOperations = new ArrayList(); - List allModels = new ArrayList(); + private void generateModelDocumentation(List files, Map models, String modelName) throws IOException { + for (String templateName : config.modelDocTemplateFiles().keySet()) { + String suffix = config.modelDocTemplateFiles().get(templateName); + String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(modelName) + suffix; + if (!config.shouldOverwrite(filename)) { + LOGGER.info("Skipped overwriting " + filename); + continue; + } + File written = processTemplateToFile(models, templateName, filename); + if (written != null) { + files.add(written); + } + } + } + + private void generateModels(List files, List allModels) { + + if (!generateModels) { + return; + } - // models final Map definitions = swagger.getDefinitions(); - if (definitions != null) { - Set modelKeys = definitions.keySet(); + if (definitions == null) { + return; + } - if(generateModels) { - if(modelsToGenerate != null && modelsToGenerate.size() > 0) { - Set updatedKeys = new HashSet(); - for(String m : modelKeys) { - if(modelsToGenerate.contains(m)) { - updatedKeys.add(m); - } - } - modelKeys = updatedKeys; + String modelNames = System.getProperty("models"); + Set modelsToGenerate = null; + if(modelNames != null && !modelNames.isEmpty()) { + modelsToGenerate = new HashSet(Arrays.asList(modelNames.split(","))); + } + + Set modelKeys = definitions.keySet(); + if(modelsToGenerate != null && !modelsToGenerate.isEmpty()) { + Set updatedKeys = new HashSet(); + for(String m : modelKeys) { + if(modelsToGenerate.contains(m)) { + updatedKeys.add(m); + } + } + modelKeys = updatedKeys; + } + + // store all processed models + Map allProcessedModels = new TreeMap(new Comparator() { + @Override + public int compare(String o1, String o2) { + Model model1 = definitions.get(o1); + Model model2 = definitions.get(o2); + + int model1InheritanceDepth = getInheritanceDepth(model1); + int model2InheritanceDepth = getInheritanceDepth(model2); + + if (model1InheritanceDepth == model2InheritanceDepth) { + return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2)); + } else if (model1InheritanceDepth > model2InheritanceDepth) { + return 1; + } else { + return -1; + } + } + + private int getInheritanceDepth(Model model) { + int inheritanceDepth = 0; + Model parent = getParent(model); + + while (parent != null) { + inheritanceDepth++; + parent = getParent(parent); } - // store all processed models - Map allProcessedModels = new TreeMap(new Comparator() { - @Override - public int compare(String o1, String o2) { - Model model1 = definitions.get(o1); - Model model2 = definitions.get(o2); + return inheritanceDepth; + } - int model1InheritanceDepth = getInheritanceDepth(model1); - int model2InheritanceDepth = getInheritanceDepth(model2); - - if (model1InheritanceDepth == model2InheritanceDepth) { - return ObjectUtils.compare(config.toModelName(o1), config.toModelName(o2)); - } else if (model1InheritanceDepth > model2InheritanceDepth) { - return 1; - } else { - return -1; - } - } - - private int getInheritanceDepth(Model model) { - int inheritanceDepth = 0; - Model parent = getParent(model); - - while (parent != null) { - inheritanceDepth++; - parent = getParent(parent); - } - - return inheritanceDepth; - } - - private Model getParent(Model model) { - if (model instanceof ComposedModel) { - Model parent = ((ComposedModel) model).getParent(); - if(parent != null) { - return definitions.get(parent.getReference()); - } - } - - return null; - } - }); - - // process models only - for (String name : modelKeys) { - try { - //don't generate models that have an import mapping - if(config.importMapping().containsKey(name)) { - LOGGER.info("Model " + name + " not imported due to import mapping"); - continue; - } - - Model model = definitions.get(name); - Map modelMap = new HashMap(); - modelMap.put(name, model); - Map models = processModels(config, modelMap, definitions); - models.put("classname", config.toModelName(name)); - models.putAll(config.additionalProperties()); - - allProcessedModels.put(name, models); - - } catch (Exception e) { - throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e); + private Model getParent(Model model) { + if (model instanceof ComposedModel) { + Model parent = ((ComposedModel) model).getParent(); + if(parent != null) { + return definitions.get(parent.getReference()); } } - // post process all processed models - allProcessedModels = config.postProcessAllModels(allProcessedModels); + return null; + } + }); - // generate files based on processed models - for (String name: allProcessedModels.keySet()) { - Map models = (Map)allProcessedModels.get(name); + // process models only + for (String name : modelKeys) { + try { + //don't generate models that have an import mapping + if(config.importMapping().containsKey(name)) { + LOGGER.info("Model " + name + " not imported due to import mapping"); + continue; + } + Model model = definitions.get(name); + Map modelMap = new HashMap(); + modelMap.put(name, model); + Map models = processModels(config, modelMap, definitions); + models.put("classname", config.toModelName(name)); + models.putAll(config.additionalProperties()); + allProcessedModels.put(name, models); + } catch (Exception e) { + throw new RuntimeException("Could not process model '" + name + "'" + ".Please make sure that your schema is correct!", e); + } + } - try { - //don't generate models that have an import mapping - if(config.importMapping().containsKey(name)) { - continue; - } + // post process all processed models + allProcessedModels = config.postProcessAllModels(allProcessedModels); - allModels.add(((List) models.get("models")).get(0)); - - for (String templateName : config.modelTemplateFiles().keySet()) { - String suffix = config.modelTemplateFiles().get(templateName); - String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; - if (!config.shouldOverwrite(filename)) { - LOGGER.info("Skipped overwriting " + filename); - continue; - } - - File written = processTemplateToFile(models, templateName, filename); - if(written != null) { - files.add(written); - } - } - - if(generateModelTests) { - // to generate model test files - for (String templateName : config.modelTestTemplateFiles().keySet()) { - String suffix = config.modelTestTemplateFiles().get(templateName); - String filename = config.modelTestFileFolder() + File.separator + config.toModelTestFilename(name) + suffix; - // do not overwrite test file that already exists - if (new File(filename).exists()) { - LOGGER.info("File exists. Skipped overwriting " + filename); - continue; - } - - File written = processTemplateToFile(models, templateName, filename); - if (written != null) { - files.add(written); - } - } - } - - if(generateModelDocumentation) { - // to generate model documentation files - for (String templateName : config.modelDocTemplateFiles().keySet()) { - String suffix = config.modelDocTemplateFiles().get(templateName); - String filename = config.modelDocFileFolder() + File.separator + config.toModelDocFilename(name) + suffix; - if (!config.shouldOverwrite(filename)) { - LOGGER.info("Skipped overwriting " + filename); - continue; - } - - File written = processTemplateToFile(models, templateName, filename); - if (written != null) { - files.add(written); - } - } - } - } catch (Exception e) { - throw new RuntimeException("Could not generate model '" + name + "'", e); + // generate files based on processed models + for (String modelName: allProcessedModels.keySet()) { + Map models = (Map)allProcessedModels.get(modelName); + try { + //don't generate models that have an import mapping + if(config.importMapping().containsKey(modelName)) { + continue; + } + allModels.add(((List) models.get("models")).get(0)); + for (String templateName : config.modelTemplateFiles().keySet()) { + String suffix = config.modelTemplateFiles().get(templateName); + String filename = config.modelFileFolder() + File.separator + config.toModelFilename(modelName) + suffix; + if (!config.shouldOverwrite(filename)) { + LOGGER.info("Skipped overwriting " + filename); + continue; + } + File written = processTemplateToFile(models, templateName, filename); + if(written != null) { + files.add(written); } } + if(generateModelTests) { + generateModelTests(files, models, modelName); + } + if(generateModelDocumentation) { + // to generate model documentation files + generateModelDocumentation(files, models, modelName); + } + } catch (Exception e) { + throw new RuntimeException("Could not generate model '" + modelName + "'", e); } } if (System.getProperty("debugModels") != null) { @@ -373,134 +325,269 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Json.prettyPrint(allModels); } - // apis + } + + private void generateApis(List files, List allOperations) { + if (!generateApis) { + return; + } Map> paths = processPaths(swagger.getPaths()); - if(generateApis) { - if(apisToGenerate != null && apisToGenerate.size() > 0) { - Map> updatedPaths = new TreeMap>(); - for(String m : paths.keySet()) { - if(apisToGenerate.contains(m)) { - updatedPaths.put(m, paths.get(m)); + Set apisToGenerate = null; + String apiNames = System.getProperty("apis"); + if(apiNames != null && !apiNames.isEmpty()) { + apisToGenerate = new HashSet(Arrays.asList(apiNames.split(","))); + } + if(apisToGenerate != null && !apisToGenerate.isEmpty()) { + Map> updatedPaths = new TreeMap>(); + for(String m : paths.keySet()) { + if(apisToGenerate.contains(m)) { + updatedPaths.put(m, paths.get(m)); + } + } + paths = updatedPaths; + } + for (String tag : paths.keySet()) { + try { + List ops = paths.get(tag); + Collections.sort(ops, new Comparator() { + @Override + public int compare(CodegenOperation one, CodegenOperation another) { + return ObjectUtils.compare(one.operationId, another.operationId); + } + }); + Map operation = processOperations(config, tag, ops); + + operation.put("basePath", basePath); + operation.put("basePathWithoutHost", basePathWithoutHost); + operation.put("contextPath", contextPath); + operation.put("baseName", tag); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); + operation.put("classFilename", config.toApiFilename(tag)); + + if(!config.vendorExtensions().isEmpty()) { + operation.put("vendorExtensions", config.vendorExtensions()); + } + + // Pass sortParamsByRequiredFlag through to the Mustache template... + boolean sortParamsByRequiredFlag = true; + if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { + sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + } + operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); + + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); + + allOperations.add(new HashMap(operation)); + for (int i = 0; i < allOperations.size(); i++) { + Map oo = (Map) allOperations.get(i); + if (i < (allOperations.size() - 1)) { + oo.put("hasMore", "true"); } } - paths = updatedPaths; - } - for (String tag : paths.keySet()) { - try { - List ops = paths.get(tag); - Collections.sort(ops, new Comparator() { - @Override - public int compare(CodegenOperation one, CodegenOperation another) { - return ObjectUtils.compare(one.operationId, another.operationId); + + for (String templateName : config.apiTemplateFiles().keySet()) { + String filename = config.apiFilename(templateName, tag); + if (!config.shouldOverwrite(filename) && new File(filename).exists()) { + LOGGER.info("Skipped overwriting " + filename); + continue; + } + + File written = processTemplateToFile(operation, templateName, filename); + if(written != null) { + files.add(written); + } + } + + if(generateApiTests) { + // to generate api test files + for (String templateName : config.apiTestTemplateFiles().keySet()) { + String filename = config.apiTestFilename(templateName, tag); + // do not overwrite test file that already exists + if (new File(filename).exists()) { + LOGGER.info("File exists. Skipped overwriting " + filename); + continue; } - }); - Map operation = processOperations(config, tag, ops); - operation.put("basePath", basePath); - operation.put("basePathWithoutHost", basePathWithoutHost); - operation.put("contextPath", contextPath); - operation.put("baseName", tag); - operation.put("modelPackage", config.modelPackage()); - operation.putAll(config.additionalProperties()); - operation.put("classname", config.toApiName(tag)); - operation.put("classVarName", config.toApiVarName(tag)); - operation.put("importPath", config.toApiImport(tag)); - operation.put("classFilename", config.toApiFilename(tag)); - - if(!config.vendorExtensions().isEmpty()) { - operation.put("vendorExtensions", config.vendorExtensions()); - } - - // Pass sortParamsByRequiredFlag through to the Mustache template... - boolean sortParamsByRequiredFlag = true; - if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { - sortParamsByRequiredFlag = Boolean.valueOf(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); - } - operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); - - processMimeTypes(swagger.getConsumes(), operation, "consumes"); - processMimeTypes(swagger.getProduces(), operation, "produces"); - - allOperations.add(new HashMap(operation)); - for (int i = 0; i < allOperations.size(); i++) { - Map oo = (Map) allOperations.get(i); - if (i < (allOperations.size() - 1)) { - oo.put("hasMore", "true"); + File written = processTemplateToFile(operation, templateName, filename); + if (written != null) { + files.add(written); } } + } - for (String templateName : config.apiTemplateFiles().keySet()) { - String filename = config.apiFilename(templateName, tag); + + if(generateApiDocumentation) { + // to generate api documentation files + for (String templateName : config.apiDocTemplateFiles().keySet()) { + String filename = config.apiDocFilename(templateName, tag); if (!config.shouldOverwrite(filename) && new File(filename).exists()) { LOGGER.info("Skipped overwriting " + filename); continue; } File written = processTemplateToFile(operation, templateName, filename); - if(written != null) { + if (written != null) { files.add(written); } } - - if(generateApiTests) { - // to generate api test files - for (String templateName : config.apiTestTemplateFiles().keySet()) { - String filename = config.apiTestFilename(templateName, tag); - // do not overwrite test file that already exists - if (new File(filename).exists()) { - LOGGER.info("File exists. Skipped overwriting " + filename); - continue; - } - - File written = processTemplateToFile(operation, templateName, filename); - if (written != null) { - files.add(written); - } - } - } - - - if(generateApiDocumentation) { - // to generate api documentation files - for (String templateName : config.apiDocTemplateFiles().keySet()) { - String filename = config.apiDocFilename(templateName, tag); - if (!config.shouldOverwrite(filename) && new File(filename).exists()) { - LOGGER.info("Skipped overwriting " + filename); - continue; - } - - File written = processTemplateToFile(operation, templateName, filename); - if (written != null) { - files.add(written); - } - } - } - - } catch (Exception e) { - throw new RuntimeException("Could not generate api file for '" + tag + "'", e); } + + } catch (Exception e) { + throw new RuntimeException("Could not generate api file for '" + tag + "'", e); } } - if (System.getProperty("debugOperations") != null) { LOGGER.info("############ Operation info ############"); Json.prettyPrint(allOperations); } - // supporting files + } + + private void generateSupportingFiles(List files, Map bundle) { + if (!generateSupportingFiles) { + return; + } + Set supportingFilesToGenerate = null; + String supportingFiles = System.getProperty("supportingFiles"); + if(supportingFiles!= null && !supportingFiles.isEmpty()) { + supportingFilesToGenerate = new HashSet(Arrays.asList(supportingFiles.split(","))); + } + + for (SupportingFile support : config.supportingFiles()) { + try { + String outputFolder = config.outputFolder(); + if (StringUtils.isNotEmpty(support.folder)) { + outputFolder += File.separator + support.folder; + } + File of = new File(outputFolder); + if (!of.isDirectory()) { + of.mkdirs(); + } + String outputFilename = outputFolder + File.separator + support.destinationFilename; + if (!config.shouldOverwrite(outputFilename)) { + LOGGER.info("Skipped overwriting " + outputFilename); + continue; + } + String templateFile; + if( support instanceof GlobalSupportingFile) { + templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile; + } else { + templateFile = getFullTemplateFile(config, support.templateFile); + } + boolean shouldGenerate = true; + if(supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) { + shouldGenerate = supportingFilesToGenerate.contains(support.destinationFilename); + } + if (!shouldGenerate){ + continue; + } + + if(ignoreProcessor.allowsFile(new File(outputFilename))) { + if (templateFile.endsWith("mustache")) { + String template = readTemplate(templateFile); + Mustache.Compiler compiler = Mustache.compiler(); + compiler = config.processCompiler(compiler); + Template tmpl = compiler + .withLoader(new Mustache.TemplateLoader() { + @Override + public Reader getTemplate(String name) { + return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); + } + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(bundle)); + files.add(new File(outputFilename)); + } else { + InputStream in = null; + + try { + in = new FileInputStream(templateFile); + } catch (Exception e) { + // continue + } + if (in == null) { + in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); + } + File outputFile = new File(outputFilename); + OutputStream out = new FileOutputStream(outputFile, false); + if (in != null) { + LOGGER.info("writing file " + outputFile); + IOUtils.copy(in, out); + } else { + LOGGER.error("can't open " + templateFile + " for input"); + } + files.add(outputFile); + } + } else { + LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); + } + } catch (Exception e) { + throw new RuntimeException("Could not generate supporting file '" + support + "'", e); + } + } + + // Consider .swagger-codegen-ignore a supporting file + // Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator + final String swaggerCodegenIgnore = ".swagger-codegen-ignore"; + String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore; + File ignoreFile = new File(ignoreFileNameTarget); + if(!ignoreFile.exists()) { + String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore; + String ignoreFileContents = readResourceContents(ignoreFileNameSource); + try { + writeToFile(ignoreFileNameTarget, ignoreFileContents); + } catch (IOException e) { + throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e); + } + files.add(ignoreFile); + } + + /* + * The following code adds default LICENSE (Apache-2.0) for all generators + * To use license other than Apache2.0, update the following file: + * modules/swagger-codegen/src/main/resources/_common/LICENSE + * + final String apache2License = "LICENSE"; + String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License; + File licenseFile = new File(licenseFileNameTarget); + String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + apache2License; + String licenseFileContents = readResourceContents(licenseFileNameSource); + try { + writeToFile(licenseFileNameTarget, licenseFileContents); + } catch (IOException e) { + throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e); + } + files.add(licenseFile); + */ + + } + + private Map buildSupportFileBundle(List allOperations, List allModels) { + Map bundle = new HashMap(); bundle.putAll(config.additionalProperties()); bundle.put("apiPackage", config.apiPackage()); Map apis = new HashMap(); apis.put("apis", allOperations); + if (swagger.getHost() != null) { bundle.put("host", swagger.getHost()); } + contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath()); + basePath = config.escapeText(getHost()); + basePathWithoutHost = config.escapeText(swagger.getBasePath()); bundle.put("swagger", this.swagger); bundle.put("basePath", basePath); bundle.put("basePathWithoutHost",basePathWithoutHost); - bundle.put("scheme", scheme); + bundle.put("scheme", getScheme()); bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); bundle.put("models", allModels); @@ -533,122 +620,33 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { LOGGER.info("############ Supporting file info ############"); Json.prettyPrint(bundle); } + return bundle; + } - if(generateSupportingFiles) { - for (SupportingFile support : config.supportingFiles()) { - try { - String outputFolder = config.outputFolder(); - if (StringUtils.isNotEmpty(support.folder)) { - outputFolder += File.separator + support.folder; - } - File of = new File(outputFolder); - if (!of.isDirectory()) { - of.mkdirs(); - } - String outputFilename = outputFolder + File.separator + support.destinationFilename; - if (!config.shouldOverwrite(outputFilename)) { - LOGGER.info("Skipped overwriting " + outputFilename); - continue; - } - String templateFile; - if( support instanceof GlobalSupportingFile) { - templateFile = config.getCommonTemplateDir() + File.separator + support.templateFile; - } else { - templateFile = getFullTemplateFile(config, support.templateFile); - } - boolean shouldGenerate = true; - if(supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) { - if(supportingFilesToGenerate.contains(support.destinationFilename)) { - shouldGenerate = true; - } - else { - shouldGenerate = false; - } - } - if(shouldGenerate) { - if(ignoreProcessor.allowsFile(new File(outputFilename))) { - if (templateFile.endsWith("mustache")) { - String template = readTemplate(templateFile); - Mustache.Compiler compiler = Mustache.compiler(); - compiler = config.processCompiler(compiler); - Template tmpl = compiler - .withLoader(new Mustache.TemplateLoader() { - @Override - public Reader getTemplate(String name) { - return getTemplateReader(getFullTemplateFile(config, name + ".mustache")); - } - }) - .defaultValue("") - .compile(template); + @Override + public List generate() { - writeToFile(outputFilename, tmpl.execute(bundle)); - files.add(new File(outputFilename)); - } else { - InputStream in = null; - - try { - in = new FileInputStream(templateFile); - } catch (Exception e) { - // continue - } - if (in == null) { - in = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(templateFile)); - } - File outputFile = new File(outputFilename); - OutputStream out = new FileOutputStream(outputFile, false); - if (in != null) { - LOGGER.info("writing file " + outputFile); - IOUtils.copy(in, out); - } else { - if (in == null) { - LOGGER.error("can't open " + templateFile + " for input"); - } - } - files.add(outputFile); - } - } else { - LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); - } - } - } catch (Exception e) { - throw new RuntimeException("Could not generate supporting file '" + support + "'", e); - } - } - - // Consider .swagger-codegen-ignore a supporting file - // Output .swagger-codegen-ignore if it doesn't exist and wasn't explicitly created by a generator - final String swaggerCodegenIgnore = ".swagger-codegen-ignore"; - String ignoreFileNameTarget = config.outputFolder() + File.separator + swaggerCodegenIgnore; - File ignoreFile = new File(ignoreFileNameTarget); - if(!ignoreFile.exists()) { - String ignoreFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + swaggerCodegenIgnore; - String ignoreFileContents = readResourceContents(ignoreFileNameSource); - try { - writeToFile(ignoreFileNameTarget, ignoreFileContents); - } catch (IOException e) { - throw new RuntimeException("Could not generate supporting file '" + swaggerCodegenIgnore + "'", e); - } - files.add(ignoreFile); - } - - /* - * The following code adds default LICENSE (Apache-2.0) for all generators - * To use license other than Apache2.0, update the following file: - * modules/swagger-codegen/src/main/resources/_common/LICENSE - * - final String apache2License = "LICENSE"; - String licenseFileNameTarget = config.outputFolder() + File.separator + apache2License; - File licenseFile = new File(licenseFileNameTarget); - String licenseFileNameSource = File.separator + config.getCommonTemplateDir() + File.separator + apache2License; - String licenseFileContents = readResourceContents(licenseFileNameSource); - try { - writeToFile(licenseFileNameTarget, licenseFileContents); - } catch (IOException e) { - throw new RuntimeException("Could not generate LICENSE file '" + apache2License + "'", e); - } - files.add(licenseFile); - */ + if (swagger == null || config == null) { + throw new RuntimeException("missing swagger input or config!"); } + configureGeneratorProperties(); + configureSwaggerInfo(); + + // resolve inline models + InlineModelResolver inlineModelResolver = new InlineModelResolver(); + inlineModelResolver.flatten(swagger); + + List files = new ArrayList(); + // models + List allModels = new ArrayList(); + generateModels(files, allModels); + // apis + List allOperations = new ArrayList(); + generateApis(files, allOperations); + + // supporting files + Map bundle = buildSupportFileBundle(allOperations, allModels); + generateSupportingFiles(files, bundle); config.processSwagger(swagger); return files; } @@ -658,7 +656,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Mustache.Compiler compiler = Mustache.compiler(); - compiler = config.processCompiler(compiler); + compiler = config.processCompiler(compiler); Template tmpl = compiler .withLoader(new Mustache.TemplateLoader() { @Override @@ -678,29 +676,30 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } private static void processMimeTypes(List mimeTypeList, Map operation, String source) { - if (mimeTypeList != null && mimeTypeList.size() > 0) { - List> c = new ArrayList>(); - int count = 0; - for (String key : mimeTypeList) { - Map mediaType = new HashMap(); - mediaType.put("mediaType", key); - count += 1; - if (count < mimeTypeList.size()) { - mediaType.put("hasMore", "true"); - } else { - mediaType.put("hasMore", null); - } - c.add(mediaType); - } - operation.put(source, c); - String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); - operation.put(flagFieldName, true); + if (mimeTypeList == null || mimeTypeList.isEmpty()){ + return; } + List> c = new ArrayList>(); + int count = 0; + for (String key : mimeTypeList) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < mimeTypeList.size()) { + mediaType.put("hasMore", "true"); + } else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + operation.put(source, c); + String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); + operation.put(flagFieldName, true); + } public Map> processPaths(Map paths) { Map> ops = new TreeMap>(); - for (String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); processOperation(resourcePath, "get", path.getGet(), ops, path); @@ -714,115 +713,107 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return ops; } - public SecuritySchemeDefinition fromSecurity(String name) { - Map map = swagger.getSecurityDefinitions(); - if (map == null) { - return null; + private void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { + if (operation == null) { + return; } - return map.get(name); - } - - public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, Path path) { - if (operation != null) { - if (System.getProperty("debugOperations") != null) { - LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation - + "\n"); - } - List tags = operation.getTags(); - if (tags == null) { - tags = new ArrayList(); - tags.add("default"); + if (System.getProperty("debugOperations") != null) { + LOGGER.info("processOperation: resourcePath= " + resourcePath + "\t;" + httpMethod + " " + operation + "\n"); + } + List tags = operation.getTags(); + if (tags == null) { + tags = new ArrayList(); + tags.add("default"); + } + /* + build up a set of parameter "ids" defined at the operation level + per the swagger 2.0 spec "A unique parameter is defined by a combination of a name and location" + i'm assuming "location" == "in" + */ + Set operationParameters = new HashSet(); + if (operation.getParameters() != null) { + for (Parameter parameter : operation.getParameters()) { + operationParameters.add(generateParameterId(parameter)); } + } - /* - build up a set of parameter "ids" defined at the operation level - per the swagger 2.0 spec "A unique parameter is defined by a combination of a name and location" - i'm assuming "location" == "in" - */ - Set operationParameters = new HashSet(); - if (operation.getParameters() != null) { - for (Parameter parameter : operation.getParameters()) { - operationParameters.add(generateParameterId(parameter)); + //need to propagate path level down to the operation + if (path.getParameters() != null) { + for (Parameter parameter : path.getParameters()) { + //skip propagation if a parameter with the same name is already defined at the operation level + if (!operationParameters.contains(generateParameterId(parameter))) { + operation.addParameter(parameter); } } + } - //need to propagate path level down to the operation - if(path.getParameters() != null) { - for (Parameter parameter : path.getParameters()) { - //skip propagation if a parameter with the same name is already defined at the operation level - if (!operationParameters.contains(generateParameterId(parameter))) { - operation.addParameter(parameter); + for (String tag : tags) { + try { + CodegenOperation codegenOperation = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); + codegenOperation.tags = new ArrayList(); + codegenOperation.tags.add(config.sanitizeTag(tag)); + config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, codegenOperation, operations); + + List>> securities = operation.getSecurity(); + if (securities == null && swagger.getSecurity() != null) { + securities = new ArrayList>>(); + for (SecurityRequirement sr : swagger.getSecurity()) { + securities.add(sr.getRequirements()); } } - } - - for (String tag : tags) { - CodegenOperation co = null; - try { - co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); - co.tags = new ArrayList(); - co.tags.add(config.sanitizeTag(tag)); - config.addOperationToGroup(config.sanitizeTag(tag), resourcePath, operation, co, operations); - - List>> securities = operation.getSecurity(); - if (securities == null && swagger.getSecurity() != null) { - securities = new ArrayList>>(); - for (SecurityRequirement sr : swagger.getSecurity()) { - securities.add(sr.getRequirements()); + if (securities == null || swagger.getSecurityDefinitions() == null) { + continue; + } + Map authMethods = new HashMap(); + for (Map> security: securities) { + for (String securityName : security.keySet()) { + SecuritySchemeDefinition securityDefinition = swagger.getSecurityDefinitions().get(securityName); + if (securityDefinition == null) { + continue; + } + if (securityDefinition instanceof OAuth2Definition) { + OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + OAuth2Definition oauth2Operation = new OAuth2Definition(); + oauth2Operation.setType(oauth2Definition.getType()); + oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); + oauth2Operation.setFlow(oauth2Definition.getFlow()); + oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); + oauth2Operation.setScopes(new HashMap()); + for (String scope : security.get(securityName)) { + if (oauth2Definition.getScopes().containsKey(scope)) { + oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); + } + } + authMethods.put(securityName, oauth2Operation); + } else { + authMethods.put(securityName, securityDefinition); } } - if (securities == null || securities.isEmpty()) { - continue; - } - Map authMethods = new HashMap(); - for (Map> security: securities) { - for (String securityName : security.keySet()) { - SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); - if (securityDefinition != null) { - if(securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; - OAuth2Definition oauth2Operation = new OAuth2Definition(); - oauth2Operation.setType(oauth2Definition.getType()); - oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); - oauth2Operation.setFlow(oauth2Definition.getFlow()); - oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); - oauth2Operation.setScopes(new HashMap()); - for (String scope : security.get(securityName)) { - if (oauth2Definition.getScopes().containsKey(scope)) { - oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); - } - } - authMethods.put(securityName, oauth2Operation); - } else { - authMethods.put(securityName, securityDefinition); - } - } - } - } - if (!authMethods.isEmpty()) { - co.authMethods = config.fromSecurity(authMethods); - co.hasAuthMethods = true; - } } - catch (Exception ex) { - String msg = "Could not process operation:\n" // + if (!authMethods.isEmpty()) { + codegenOperation.authMethods = config.fromSecurity(authMethods); + codegenOperation.hasAuthMethods = true; + } + } + catch (Exception ex) { + String msg = "Could not process operation:\n" // + " Tag: " + tag + "\n"// + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// + " Definitions: " + swagger.getDefinitions() + "\n" // + " Exception: " + ex.getMessage(); - throw new RuntimeException(msg, ex); - } + throw new RuntimeException(msg, ex); } } + } private static String generateParameterId(Parameter parameter) { return parameter.getName() + ":" + parameter.getIn(); } - @SuppressWarnings("static-method") - public Map processOperations(CodegenConfig config, String tag, List ops) { + + private Map processOperations(CodegenConfig config, String tag, List ops) { Map operations = new HashMap(); Map objs = new HashMap(); objs.put("classname", config.toApiName(tag)); @@ -869,7 +860,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (imports.size() > 0) { operations.put("hasImport", true); } - config.postProcessOperations(operations); if (objs.size() > 0) { List os = (List) objs.get("operation"); @@ -882,8 +872,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return operations; } - @SuppressWarnings("static-method") - public Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { + + private Map processModels(CodegenConfig config, Map definitions, Map allDefinitions) { Map objs = new HashMap(); objs.put("package", config.modelPackage()); List models = new ArrayList(); @@ -899,7 +889,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { allImports.addAll(cm.imports); } objs.put("models", models); - Set importSet = new TreeSet(); for (String nextImport : allImports) { String mapping = config.importMapping().get(nextImport); @@ -915,17 +904,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { importSet.add(mapping); } } - List> imports = new ArrayList>(); for(String s: importSet) { Map item = new HashMap(); item.put("import", s); imports.add(item); } - objs.put("imports", imports); config.postProcessModels(objs); - return objs; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 4f11ea6fa38..829e2604f1d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -449,7 +449,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; } return super.getTypeDeclaration(p); @@ -639,7 +638,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); codegenModel = AbstractJavaCodegen.reconcileInlineEnums(codegenModel, parentCodegenModel); } - return codegenModel; } @@ -667,7 +665,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code model.imports.add("ApiModelProperty"); model.imports.add("ApiModel"); } - return; } @Override @@ -712,26 +709,27 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public void preprocessSwagger(Swagger swagger) { - if (swagger != null && swagger.getPaths() != null) { - for (String pathname : swagger.getPaths().keySet()) { - Path path = swagger.getPath(pathname); - if (path.getOperations() != null) { - for (Operation operation : path.getOperations()) { - boolean hasFormParameters = false; - for (Parameter parameter : operation.getParameters()) { - if (parameter instanceof FormParameter) { - hasFormParameters = true; - } - } - - String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; - String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() - ? defaultContentType : operation.getConsumes().get(0); - String accepts = getAccept(operation); - operation.setVendorExtension("x-contentType", contentType); - operation.setVendorExtension("x-accepts", accepts); + if (swagger == null || swagger.getPaths() == null){ + return; + } + for (String pathname : swagger.getPaths().keySet()) { + Path path = swagger.getPath(pathname); + if (path.getOperations() == null){ + continue; + } + for (Operation operation : path.getOperations()) { + boolean hasFormParameters = false; + for (Parameter parameter : operation.getParameters()) { + if (parameter instanceof FormParameter) { + hasFormParameters = true; } } + String defaultContentType = hasFormParameters ? "application/x-www-form-urlencoded" : "application/json"; + String contentType = operation.getConsumes() == null || operation.getConsumes().isEmpty() + ? defaultContentType : operation.getConsumes().get(0); + String accepts = getAccept(operation); + operation.setVendorExtension("x-contentType", contentType); + operation.setVendorExtension("x-accepts", accepts); } } } @@ -820,9 +818,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { CodegenOperation op = super.fromOperation(path, httpMethod, operation, definitions, swagger); - op.path = sanitizePath(op.path); - return op; } @@ -834,43 +830,43 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code // Because the child models extend the parents, the enums will be available via the parent. // Only bother with reconciliation if the parent model has enums. - if (parentCodegenModel.hasEnums) { + if (!parentCodegenModel.hasEnums) { + return codegenModel; + } - // Get the properties for the parent and child models - final List parentModelCodegenProperties = parentCodegenModel.vars; - List codegenProperties = codegenModel.vars; + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; - // Iterate over all of the parent model properties - boolean removedChildEnum = false; - for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { - // Look for enums - if (parentModelCodegenPropery.isEnum) { - // Now that we have found an enum in the parent class, - // and search the child class for the same enum. - Iterator iterator = codegenProperties.iterator(); - while (iterator.hasNext()) { - CodegenProperty codegenProperty = iterator.next(); - if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { - // We found an enum in the child class that is - // a duplicate of the one in the parent, so remove it. - iterator.remove(); - removedChildEnum = true; - } + // Iterate over all of the parent model properties + boolean removedChildEnum = false; + for (CodegenProperty parentModelCodegenPropery : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenPropery.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenPropery)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildEnum = true; } } } - - if(removedChildEnum) { - // If we removed an entry from this model's vars, we need to ensure hasMore is updated - int count = 0, numVars = codegenProperties.size(); - for(CodegenProperty codegenProperty : codegenProperties) { - count += 1; - codegenProperty.hasMore = (count < numVars) ? true : null; - } - codegenModel.vars = codegenProperties; - } } + if(removedChildEnum) { + // If we removed an entry from this model's vars, we need to ensure hasMore is updated + int count = 0, numVars = codegenProperties.size(); + for(CodegenProperty codegenProperty : codegenProperties) { + count += 1; + codegenProperty.hasMore = (count < numVars) ? true : null; + } + codegenModel.vars = codegenProperties; + } return codegenModel; } From bcc7e69fcc0d1a6d6e020c175dce752ee3c4e215 Mon Sep 17 00:00:00 2001 From: cbornet Date: Wed, 23 Nov 2016 18:40:02 +0100 Subject: [PATCH 103/269] [Flask] Add packaging support --- .../languages/FlaskConnexionCodegen.java | 99 +++++++++---------- .../resources/flaskConnexion/README.mustache | 15 ++- ..._controller.mustache => __init__.mustache} | 0 .../flaskConnexion/__init__test.mustache | 2 +- .../flaskConnexion/__main__.mustache | 16 +++ .../flaskConnexion/base_model_.mustache | 2 +- .../flaskConnexion/controller.mustache | 2 +- .../{app.mustache => encoder.mustache} | 17 +--- .../flaskConnexion/git_push.sh.mustache | 52 ++++++++++ .../flaskConnexion/gitignore.mustache | 64 ++++++++++++ .../resources/flaskConnexion/model.mustache | 2 +- .../flaskConnexion/requirements.mustache | 6 ++ .../resources/flaskConnexion/setup.mustache | 33 +++++++ .../flaskConnexion/test-requirements.mustache | 6 ++ .../resources/flaskConnexion/tox.mustache | 10 ++ .../resources/flaskConnexion/travis.mustache | 16 +++ .../flaskConnexion-python2/.gitignore | 64 ++++++++++++ .../flaskConnexion-python2/.travis.yml | 14 +++ .../petstore/flaskConnexion-python2/README.md | 11 ++- .../petstore/flaskConnexion-python2/app.py | 29 ------ .../flaskConnexion-python2/git_push.sh | 52 ++++++++++ .../flaskConnexion-python2/requirements.txt | 4 + .../petstore/flaskConnexion-python2/setup.py | 33 +++++++ .../{ => swagger_server}/__init__.py | 0 .../swagger_server/__main__.py | 11 +++ .../controllers/__init__.py | 0 .../controllers/pet_controller.py | 6 +- .../controllers/store_controller.py | 4 +- .../controllers/user_controller.py | 4 +- .../swagger_server/encoder.py | 19 ++++ .../{ => swagger_server}/models/__init__.py | 0 .../models/api_response.py | 2 +- .../models/base_model_.py | 2 +- .../{ => swagger_server}/models/category.py | 2 +- .../{ => swagger_server}/models/order.py | 2 +- .../{ => swagger_server}/models/pet.py | 6 +- .../{ => swagger_server}/models/tag.py | 2 +- .../{ => swagger_server}/models/user.py | 2 +- .../{ => swagger_server}/swagger/swagger.yaml | 40 ++++---- .../{ => swagger_server}/test/__init__.py | 2 +- .../test/test_pet_controller.py | 4 +- .../test/test_store_controller.py | 2 +- .../test/test_user_controller.py | 2 +- .../{ => swagger_server}/util.py | 0 .../test-requirements.txt | 6 ++ .../petstore/flaskConnexion-python2/tox.ini | 10 ++ .../server/petstore/flaskConnexion/.gitignore | 64 ++++++++++++ .../petstore/flaskConnexion/.travis.yml | 13 +++ .../server/petstore/flaskConnexion/README.md | 11 ++- samples/server/petstore/flaskConnexion/app.py | 29 ------ .../petstore/flaskConnexion/git_push.sh | 52 ++++++++++ .../petstore/flaskConnexion/requirements.txt | 3 + .../server/petstore/flaskConnexion/setup.py | 33 +++++++ .../{ => swagger_server}/__init__.py | 0 .../flaskConnexion/swagger_server/__main__.py | 11 +++ .../controllers/__init__.py | 0 .../controllers/pet_controller.py | 6 +- .../controllers/store_controller.py | 4 +- .../controllers/user_controller.py | 4 +- .../flaskConnexion/swagger_server/encoder.py | 19 ++++ .../{ => swagger_server}/models/__init__.py | 0 .../models/api_response.py | 2 +- .../models/base_model_.py | 2 +- .../{ => swagger_server}/models/category.py | 2 +- .../{ => swagger_server}/models/order.py | 2 +- .../{ => swagger_server}/models/pet.py | 6 +- .../{ => swagger_server}/models/tag.py | 2 +- .../{ => swagger_server}/models/user.py | 2 +- .../{ => swagger_server}/swagger/swagger.yaml | 40 ++++---- .../{ => swagger_server}/test/__init__.py | 2 +- .../test/test_pet_controller.py | 4 +- .../test/test_store_controller.py | 2 +- .../test/test_user_controller.py | 2 +- .../{ => swagger_server}/util.py | 0 .../flaskConnexion/test-requirements.txt | 6 ++ .../server/petstore/flaskConnexion/tox.ini | 10 ++ 76 files changed, 788 insertions(+), 222 deletions(-) rename modules/swagger-codegen/src/main/resources/flaskConnexion/{__init__controller.mustache => __init__.mustache} (100%) create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache rename modules/swagger-codegen/src/main/resources/flaskConnexion/{app.mustache => encoder.mustache} (55%) create mode 100755 modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/gitignore.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/requirements.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/test-requirements.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache create mode 100644 modules/swagger-codegen/src/main/resources/flaskConnexion/travis.mustache create mode 100644 samples/server/petstore/flaskConnexion-python2/.gitignore create mode 100644 samples/server/petstore/flaskConnexion-python2/.travis.yml delete mode 100644 samples/server/petstore/flaskConnexion-python2/app.py create mode 100644 samples/server/petstore/flaskConnexion-python2/git_push.sh create mode 100644 samples/server/petstore/flaskConnexion-python2/requirements.txt create mode 100644 samples/server/petstore/flaskConnexion-python2/setup.py rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/__init__.py (100%) create mode 100644 samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/controllers/__init__.py (100%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/controllers/pet_controller.py (93%) rename samples/server/petstore/{flaskConnexion => flaskConnexion-python2/swagger_server}/controllers/store_controller.py (92%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/controllers/user_controller.py (95%) create mode 100644 samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/__init__.py (100%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/api_response.py (98%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/base_model_.py (98%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/category.py (98%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/order.py (99%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/pet.py (97%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/tag.py (97%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/models/user.py (99%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/swagger/swagger.yaml (91%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/test/__init__.py (91%) rename samples/server/petstore/{flaskConnexion => flaskConnexion-python2/swagger_server}/test/test_pet_controller.py (97%) rename samples/server/petstore/{flaskConnexion => flaskConnexion-python2/swagger_server}/test/test_store_controller.py (97%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/test/test_user_controller.py (98%) rename samples/server/petstore/flaskConnexion-python2/{ => swagger_server}/util.py (100%) create mode 100644 samples/server/petstore/flaskConnexion-python2/test-requirements.txt create mode 100644 samples/server/petstore/flaskConnexion-python2/tox.ini create mode 100644 samples/server/petstore/flaskConnexion/.gitignore create mode 100644 samples/server/petstore/flaskConnexion/.travis.yml delete mode 100644 samples/server/petstore/flaskConnexion/app.py create mode 100644 samples/server/petstore/flaskConnexion/git_push.sh create mode 100644 samples/server/petstore/flaskConnexion/requirements.txt create mode 100644 samples/server/petstore/flaskConnexion/setup.py rename samples/server/petstore/flaskConnexion/{ => swagger_server}/__init__.py (100%) create mode 100644 samples/server/petstore/flaskConnexion/swagger_server/__main__.py rename samples/server/petstore/flaskConnexion/{ => swagger_server}/controllers/__init__.py (100%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/controllers/pet_controller.py (93%) rename samples/server/petstore/{flaskConnexion-python2 => flaskConnexion/swagger_server}/controllers/store_controller.py (92%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/controllers/user_controller.py (95%) create mode 100644 samples/server/petstore/flaskConnexion/swagger_server/encoder.py rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/__init__.py (100%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/api_response.py (98%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/base_model_.py (98%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/category.py (98%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/order.py (99%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/pet.py (97%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/tag.py (97%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/models/user.py (99%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/swagger/swagger.yaml (91%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/test/__init__.py (91%) rename samples/server/petstore/{flaskConnexion-python2 => flaskConnexion/swagger_server}/test/test_pet_controller.py (97%) rename samples/server/petstore/{flaskConnexion-python2 => flaskConnexion/swagger_server}/test/test_store_controller.py (97%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/test/test_user_controller.py (98%) rename samples/server/petstore/flaskConnexion/{ => swagger_server}/util.py (100%) create mode 100644 samples/server/petstore/flaskConnexion/test-requirements.txt create mode 100644 samples/server/petstore/flaskConnexion/tox.ini diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 3df5b15d70c..54bdb85c835 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -29,9 +29,9 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf public static final String DEFAULT_CONTROLLER = "defaultController"; public static final String SUPPORT_PYTHON2= "supportPython2"; - protected String apiVersion = "1.0.0"; protected int serverPort = 8080; - protected String projectName = "swagger-server"; + protected String packageName; + protected String packageVersion; protected String controllerPackage; protected String defaultController; @@ -91,7 +91,6 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf * Additional Properties. These values can be passed to the templates and * are available in models, apis, and supporting files */ - additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); /* @@ -99,28 +98,19 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf * entire object tree available. If the input file has a suffix of `.mustache * it will be processed by the template engine. Otherwise, it will be copied */ + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("setup.mustache", "", "setup.py")); + supportingFiles.add(new SupportingFile("tox.mustache", "", "tox.ini")); + supportingFiles.add(new SupportingFile("test-requirements.mustache", "", "test-requirements.txt")); + supportingFiles.add(new SupportingFile("requirements.mustache", "", "requirements.txt")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("travis.mustache", "", ".travis.yml")); - supportingFiles.add(new SupportingFile("swagger.mustache", - "swagger", - "swagger.yaml") - ); - supportingFiles.add(new SupportingFile("app.mustache", - "", - "app.py") - ); - supportingFiles.add(new SupportingFile("util.mustache", - "", - "util.py") - ); - supportingFiles.add(new SupportingFile("README.mustache", - "", - "README.md") - ); - supportingFiles.add(new SupportingFile("__init__controller.mustache", - "", - "__init__.py") - ); - + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") + .defaultValue("swagger_server")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "python package version.") + .defaultValue("1.0.0")); cliOptions.add(new CliOption(CONTROLLER_PACKAGE, "controller package"). defaultValue("controllers")); cliOptions.add(new CliOption(DEFAULT_CONTROLLER, "default controller"). @@ -134,48 +124,47 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf super.processOpts(); //apiTemplateFiles.clear(); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + setPackageName("swagger_server"); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, this.packageName); + } + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } else { + setPackageVersion("1.0.0"); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, this.packageVersion); + } if (additionalProperties.containsKey(CONTROLLER_PACKAGE)) { this.controllerPackage = additionalProperties.get(CONTROLLER_PACKAGE).toString(); - } - else { + } else { this.controllerPackage = "controllers"; additionalProperties.put(CONTROLLER_PACKAGE, this.controllerPackage); } - if (additionalProperties.containsKey(DEFAULT_CONTROLLER)) { this.defaultController = additionalProperties.get(DEFAULT_CONTROLLER).toString(); - } - else { + } else { this.defaultController = "default_controller"; additionalProperties.put(DEFAULT_CONTROLLER, this.defaultController); } - if (Boolean.TRUE.equals(additionalProperties.get(SUPPORT_PYTHON2))) { additionalProperties.put(SUPPORT_PYTHON2, Boolean.TRUE); typeMapping.put("long", "long"); } + supportingFiles.add(new SupportingFile("__init__.mustache", packageName, "__init__.py")); + supportingFiles.add(new SupportingFile("__main__.mustache", packageName, "__main__.py")); + supportingFiles.add(new SupportingFile("encoder.mustache", packageName, "encoder.py")); + supportingFiles.add(new SupportingFile("util.mustache", packageName, "util.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", packageName + File.separatorChar + controllerPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", packageName + File.separatorChar + modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("base_model_.mustache", packageName + File.separatorChar + modelPackage, "base_model_.py")); + supportingFiles.add(new SupportingFile("__init__test.mustache", packageName + File.separatorChar + testPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("swagger.mustache", packageName + File.separatorChar + "swagger", "swagger.yaml")); - if(!new java.io.File(controllerPackage + File.separator + defaultController + ".py").exists()) { - supportingFiles.add(new SupportingFile("__init__controller.mustache", - controllerPackage, - "__init__.py") - ); - } - - supportingFiles.add(new SupportingFile("__init__model.mustache", - modelPackage, - "__init__.py") - ); - - supportingFiles.add(new SupportingFile("base_model_.mustache", - modelPackage, - "base_model_.py") - ); - - supportingFiles.add(new SupportingFile("__init__test.mustache", - testPackage, - "__init__.py") - ); + modelPackage = packageName + "." + modelPackage; + controllerPackage = packageName + "." + controllerPackage; + testPackage = packageName + "." + testPackage; } private static String dropDots(String str) { @@ -628,6 +617,14 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf p.example = example; } + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + @Override public String escapeQuotationMark(String input) { diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache index 2d64ddbccf6..f8471d67b95 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/README.mustache @@ -7,16 +7,16 @@ is an example of building a swagger-enabled Flask server. This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. -To run the server, please execute the following: +To run the server, please execute the following from the root directory: ``` {{#supportPython2}} -sudo pip install -U connexion flask_testing typing # install Connexion from PyPI -python app.py +pip install -r requirements.txt +python -m {{packageName}} {{/supportPython2}} {{^supportPython2}} -sudo pip3 install -U connexion flask_testing # install Connexion from PyPI -python3 app.py +pip3 install -r requirements.txt +python3 -m {{packageName}} {{/supportPython2}} ``` @@ -32,3 +32,8 @@ Your Swagger definition lives here: http://localhost:{{serverPort}}{{contextPath}}/swagger.json ``` +To launch the integration tests, use tox: +``` +sudo pip install tox +tox +``` diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/flaskConnexion/__init__controller.mustache rename to modules/swagger-codegen/src/main/resources/flaskConnexion/__init__.mustache diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache index 352991098f1..77b10c3a012 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__init__test.mustache @@ -1,5 +1,5 @@ from flask_testing import TestCase -from app import JSONEncoder +from ..encoder import JSONEncoder import connexion import logging diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache new file mode 100644 index 00000000000..efbea8409c5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/__main__.mustache @@ -0,0 +1,16 @@ +{{#supportPython2}} +#!/usr/bin/env python +{{/supportPython2}} +{{^supportPython2}} +#!/usr/bin/env python3 +{{/supportPython2}} + +import connexion +from .encoder import JSONEncoder + + +if __name__ == '__main__': + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) + app.run(port={{serverPort}}) diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache index ba7b5b23dc1..6e3464c7019 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/base_model_.mustache @@ -3,7 +3,7 @@ from pprint import pformat from typing import TypeVar, Type {{/supportPython2}} from six import iteritems -from util import deserialize_model +from ..util import deserialize_model {{^supportPython2}} T = TypeVar('T') diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache index f762017284d..8fc01dbd7ac 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/controller.mustache @@ -4,7 +4,7 @@ import connexion from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime {{#operations}} {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache similarity index 55% rename from modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache rename to modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache index 8428dedddaa..2f2c5416708 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/app.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/encoder.mustache @@ -1,11 +1,3 @@ -{{#supportPython2}} -#!/usr/bin/env python -{{/supportPython2}} -{{^supportPython2}} -#!/usr/bin/env python3 -{{/supportPython2}} - -import connexion from connexion.decorators import produces from six import iteritems from {{modelPackage}}.base_model_ import Model @@ -24,11 +16,4 @@ class JSONEncoder(produces.JSONEncoder): attr = o.attribute_map[attr] dikt[attr] = value return dikt - return produces.JSONEncoder.default(self, o) - - -if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': '{{appDescription}}'}) - app.run(port={{serverPort}}) + return produces.JSONEncoder.default(self, o) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/gitignore.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/gitignore.mustache new file mode 100644 index 00000000000..a655050c263 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/gitignore.mustache @@ -0,0 +1,64 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.python-version + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache index 36b0af83c69..9a0b4f89247 100644 --- a/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/model.mustache @@ -6,7 +6,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model {{#models}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/requirements.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/requirements.mustache new file mode 100644 index 00000000000..b36f4a65b57 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/requirements.mustache @@ -0,0 +1,6 @@ +connexion == 1.0.129 +python_dateutil == 2.6.0 +{{#supportPython2}} +typing == 3.5.2.2 +{{/supportPython2}} +setuptools >= 21.0.0 diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache new file mode 100644 index 00000000000..dd2dea6aeed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/setup.mustache @@ -0,0 +1,33 @@ +# coding: utf-8 + +import sys +from setuptools import setup, find_packages + +NAME = "{{packageName}}" +VERSION = "{{packageVersion}}" +{{#apiInfo}}{{#apis}}{{^hasMore}} +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["connexion"] + +setup( + name=NAME, + version=VERSION, + description="{{appName}}", + author_email="{{infoEmail}}", + url="{{packageUrl}}", + keywords=["Swagger", "{{appName}}"], + install_requires=REQUIRES, + packages=find_packages(), + package_data={'': ['swagger/swagger.yaml']}, + include_package_data=True, + long_description="""\ + {{appDescription}} + """ +) +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/test-requirements.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/test-requirements.mustache new file mode 100644 index 00000000000..7f8d96e6b40 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/test-requirements.mustache @@ -0,0 +1,6 @@ +flask_testing==0.6.1 +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache new file mode 100644 index 00000000000..5ad8fe6c031 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/tox.mustache @@ -0,0 +1,10 @@ +[tox] +envlist = {{#supportPython2}}py27, {{/supportPython2}}py35 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/flaskConnexion/travis.mustache b/modules/swagger-codegen/src/main/resources/flaskConnexion/travis.mustache new file mode 100644 index 00000000000..167826e42b4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/flaskConnexion/travis.mustache @@ -0,0 +1,16 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: +{{#supportPython2}} + - "2.7" +{{/supportPython2}} + - "3.2" + - "3.3" + - "3.4" + - "3.5" + #- "3.5-dev" # 3.5 development branch + #- "nightly" # points to the latest development branch e.g. 3.6-dev +# command to install dependencies +install: "pip install -r requirements.txt" +# command to run tests +script: nosetests diff --git a/samples/server/petstore/flaskConnexion-python2/.gitignore b/samples/server/petstore/flaskConnexion-python2/.gitignore new file mode 100644 index 00000000000..a655050c263 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/.gitignore @@ -0,0 +1,64 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.python-version + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/server/petstore/flaskConnexion-python2/.travis.yml b/samples/server/petstore/flaskConnexion-python2/.travis.yml new file mode 100644 index 00000000000..86211e2d4a2 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/.travis.yml @@ -0,0 +1,14 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "2.7" + - "3.2" + - "3.3" + - "3.4" + - "3.5" + #- "3.5-dev" # 3.5 development branch + #- "nightly" # points to the latest development branch e.g. 3.6-dev +# command to install dependencies +install: "pip install -r requirements.txt" +# command to run tests +script: nosetests diff --git a/samples/server/petstore/flaskConnexion-python2/README.md b/samples/server/petstore/flaskConnexion-python2/README.md index b744fc39f9a..5352812b279 100644 --- a/samples/server/petstore/flaskConnexion-python2/README.md +++ b/samples/server/petstore/flaskConnexion-python2/README.md @@ -7,11 +7,11 @@ is an example of building a swagger-enabled Flask server. This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. -To run the server, please execute the following: +To run the server, please execute the following from the root directory: ``` -sudo pip install -U connexion flask_testing typing # install Connexion from PyPI -python app.py +pip install -r requirements.txt +python -m swagger_server ``` and open your browser to here: @@ -26,3 +26,8 @@ Your Swagger definition lives here: http://localhost:8080/v2/swagger.json ``` +To launch the integration tests, use tox: +``` +sudo pip install tox +tox +``` diff --git a/samples/server/petstore/flaskConnexion-python2/app.py b/samples/server/petstore/flaskConnexion-python2/app.py deleted file mode 100644 index 413af17ec79..00000000000 --- a/samples/server/petstore/flaskConnexion-python2/app.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python - -import connexion -from connexion.decorators import produces -from six import iteritems -from models.base_model_ import Model - - -class JSONEncoder(produces.JSONEncoder): - include_nulls = False - - def default(self, o): - if isinstance(o, Model): - dikt = {} - for attr, _ in iteritems(o.swagger_types): - value = getattr(o, attr) - if value is None and not self.include_nulls: - continue - attr = o.attribute_map[attr] - dikt[attr] = value - return dikt - return produces.JSONEncoder.default(self, o) - - -if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) - app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion-python2/git_push.sh b/samples/server/petstore/flaskConnexion-python2/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/server/petstore/flaskConnexion-python2/requirements.txt b/samples/server/petstore/flaskConnexion-python2/requirements.txt new file mode 100644 index 00000000000..38bbf3e74cb --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/requirements.txt @@ -0,0 +1,4 @@ +connexion == 1.0.129 +python_dateutil == 2.6.0 +typing == 3.5.2.2 +setuptools >= 21.0.0 diff --git a/samples/server/petstore/flaskConnexion-python2/setup.py b/samples/server/petstore/flaskConnexion-python2/setup.py new file mode 100644 index 00000000000..7a1ce575d35 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/setup.py @@ -0,0 +1,33 @@ +# coding: utf-8 + +import sys +from setuptools import setup, find_packages + +NAME = "swagger_server" +VERSION = "1.0.0" + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["connexion"] + +setup( + name=NAME, + version=VERSION, + description="Swagger Petstore", + author_email="apiteam@swagger.io", + url="", + keywords=["Swagger", "Swagger Petstore"], + install_requires=REQUIRES, + packages=find_packages(), + package_data={'': ['swagger/swagger.yaml']}, + include_package_data=True, + long_description="""\ + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + """ +) + diff --git a/samples/server/petstore/flaskConnexion-python2/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion-python2/__init__.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/__init__.py diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py new file mode 100644 index 00000000000..a85a5591ece --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/__main__.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import connexion +from .encoder import JSONEncoder + + +if __name__ == '__main__': + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) + app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion-python2/controllers/__init__.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/__init__.py diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py similarity index 93% rename from samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py index 0a1be8f8863..5a999aae88f 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/pet_controller.py @@ -1,10 +1,10 @@ import connexion -from models.api_response import ApiResponse -from models.pet import Pet +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.pet import Pet from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def add_pet(body): diff --git a/samples/server/petstore/flaskConnexion/controllers/store_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py similarity index 92% rename from samples/server/petstore/flaskConnexion/controllers/store_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py index 5373cbf5f71..0cdcaf445dc 100644 --- a/samples/server/petstore/flaskConnexion/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/store_controller.py @@ -1,9 +1,9 @@ import connexion -from models.order import Order +from swagger_server.models.order import Order from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def delete_order(orderId): diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py similarity index 95% rename from samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py index 0e406488a7f..9a88626c5b8 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/controllers/user_controller.py @@ -1,9 +1,9 @@ import connexion -from models.user import User +from swagger_server.models.user import User from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def create_user(body): diff --git a/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py new file mode 100644 index 00000000000..90988e4d3ea --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/encoder.py @@ -0,0 +1,19 @@ +from connexion.decorators import produces +from six import iteritems +from swagger_server.models.base_model_ import Model + + +class JSONEncoder(produces.JSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return produces.JSONEncoder.default(self, o) \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion-python2/models/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion-python2/models/__init__.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/__init__.py diff --git a/samples/server/petstore/flaskConnexion-python2/models/api_response.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py similarity index 98% rename from samples/server/petstore/flaskConnexion-python2/models/api_response.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py index aeeee173602..0868d2a1049 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/api_response.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/api_response.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class ApiResponse(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/models/base_model_.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py similarity index 98% rename from samples/server/petstore/flaskConnexion-python2/models/base_model_.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py index 61136d40eff..30a7a03577a 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/base_model_.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/base_model_.py @@ -1,6 +1,6 @@ from pprint import pformat from six import iteritems -from util import deserialize_model +from ..util import deserialize_model class Model(object): diff --git a/samples/server/petstore/flaskConnexion-python2/models/category.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py similarity index 98% rename from samples/server/petstore/flaskConnexion-python2/models/category.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py index 82fd59fe337..440b19f7a82 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/category.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/category.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Category(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/models/order.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py similarity index 99% rename from samples/server/petstore/flaskConnexion-python2/models/order.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py index 20c6fbe4102..a3cb599defa 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/order.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/order.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Order(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/models/pet.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py similarity index 97% rename from samples/server/petstore/flaskConnexion-python2/models/pet.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py index 5bd32865fbd..074f5d2366c 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/pet.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/pet.py @@ -1,12 +1,12 @@ # coding: utf-8 from __future__ import absolute_import -from models.category import Category -from models.tag import Tag +from swagger_server.models.category import Category +from swagger_server.models.tag import Tag from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Pet(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/models/tag.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py similarity index 97% rename from samples/server/petstore/flaskConnexion-python2/models/tag.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py index e397ac90255..6ff4243a1a4 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/tag.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/tag.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Tag(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/models/user.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py similarity index 99% rename from samples/server/petstore/flaskConnexion-python2/models/user.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py index 134dfd7a892..715832d2f01 100644 --- a/samples/server/petstore/flaskConnexion-python2/models/user.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/models/user.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class User(Model): diff --git a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml similarity index 91% rename from samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml rename to samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml index 3d22ab2d847..9d948b2124f 100644 --- a/samples/server/petstore/flaskConnexion-python2/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/swagger/swagger.yaml @@ -58,7 +58,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" put: tags: - "pet" @@ -89,7 +89,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/findByStatus: get: tags: @@ -127,7 +127,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/findByTags: get: tags: @@ -161,7 +161,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/{petId}: get: tags: @@ -190,7 +190,7 @@ paths: description: "Pet not found" security: - api_key: [] - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" post: tags: - "pet" @@ -226,7 +226,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" delete: tags: - "pet" @@ -254,7 +254,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/{petId}/uploadImage: post: tags: @@ -292,7 +292,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /store/inventory: get: tags: @@ -313,7 +313,7 @@ paths: format: "int32" security: - api_key: [] - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /store/order: post: tags: @@ -338,7 +338,7 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /store/order/{orderId}: get: tags: @@ -368,7 +368,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" delete: tags: - "store" @@ -391,7 +391,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /user: post: tags: @@ -412,7 +412,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/createWithArray: post: tags: @@ -435,7 +435,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/createWithList: post: tags: @@ -458,7 +458,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/login: get: tags: @@ -496,7 +496,7 @@ paths: description: "date in UTC when toekn expires" 400: description: "Invalid username/password supplied" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/logout: get: tags: @@ -511,7 +511,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/{username}: get: tags: @@ -537,7 +537,7 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" put: tags: - "user" @@ -564,7 +564,7 @@ paths: description: "Invalid user supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" delete: tags: - "user" @@ -585,7 +585,7 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" securityDefinitions: petstore_auth: type: "oauth2" diff --git a/samples/server/petstore/flaskConnexion-python2/test/__init__.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py similarity index 91% rename from samples/server/petstore/flaskConnexion-python2/test/__init__.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py index 352991098f1..77b10c3a012 100644 --- a/samples/server/petstore/flaskConnexion-python2/test/__init__.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/__init__.py @@ -1,5 +1,5 @@ from flask_testing import TestCase -from app import JSONEncoder +from ..encoder import JSONEncoder import connexion import logging diff --git a/samples/server/petstore/flaskConnexion/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py similarity index 97% rename from samples/server/petstore/flaskConnexion/test/test_pet_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py index 31e3b3fcb6b..b99269a991a 100644 --- a/samples/server/petstore/flaskConnexion/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_pet_controller.py @@ -2,8 +2,8 @@ from __future__ import absolute_import -from models.api_response import ApiResponse -from models.pet import Pet +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.pet import Pet from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion/test/test_store_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py similarity index 97% rename from samples/server/petstore/flaskConnexion/test/test_store_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py index 33a007ae195..0a5360b4e25 100644 --- a/samples/server/petstore/flaskConnexion/test/test_store_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_store_controller.py @@ -2,7 +2,7 @@ from __future__ import absolute_import -from models.order import Order +from swagger_server.models.order import Order from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py similarity index 98% rename from samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py index 52dacf3df32..867de3c0150 100644 --- a/samples/server/petstore/flaskConnexion-python2/test/test_user_controller.py +++ b/samples/server/petstore/flaskConnexion-python2/swagger_server/test/test_user_controller.py @@ -2,7 +2,7 @@ from __future__ import absolute_import -from models.user import User +from swagger_server.models.user import User from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion-python2/util.py b/samples/server/petstore/flaskConnexion-python2/swagger_server/util.py similarity index 100% rename from samples/server/petstore/flaskConnexion-python2/util.py rename to samples/server/petstore/flaskConnexion-python2/swagger_server/util.py diff --git a/samples/server/petstore/flaskConnexion-python2/test-requirements.txt b/samples/server/petstore/flaskConnexion-python2/test-requirements.txt new file mode 100644 index 00000000000..7f8d96e6b40 --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/test-requirements.txt @@ -0,0 +1,6 @@ +flask_testing==0.6.1 +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/samples/server/petstore/flaskConnexion-python2/tox.ini b/samples/server/petstore/flaskConnexion-python2/tox.ini new file mode 100644 index 00000000000..fe94589593a --- /dev/null +++ b/samples/server/petstore/flaskConnexion-python2/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py27, py35 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion/.gitignore b/samples/server/petstore/flaskConnexion/.gitignore new file mode 100644 index 00000000000..a655050c263 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/.gitignore @@ -0,0 +1,64 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +venv/ +.python-version + +# Translations +*.mo +*.pot + +# Django stuff: +*.log + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +#Ipython Notebook +.ipynb_checkpoints diff --git a/samples/server/petstore/flaskConnexion/.travis.yml b/samples/server/petstore/flaskConnexion/.travis.yml new file mode 100644 index 00000000000..dd6c4450aa9 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/.travis.yml @@ -0,0 +1,13 @@ +# ref: https://docs.travis-ci.com/user/languages/python +language: python +python: + - "3.2" + - "3.3" + - "3.4" + - "3.5" + #- "3.5-dev" # 3.5 development branch + #- "nightly" # points to the latest development branch e.g. 3.6-dev +# command to install dependencies +install: "pip install -r requirements.txt" +# command to run tests +script: nosetests diff --git a/samples/server/petstore/flaskConnexion/README.md b/samples/server/petstore/flaskConnexion/README.md index 0ba312c48ac..91b687abcf4 100644 --- a/samples/server/petstore/flaskConnexion/README.md +++ b/samples/server/petstore/flaskConnexion/README.md @@ -7,11 +7,11 @@ is an example of building a swagger-enabled Flask server. This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. -To run the server, please execute the following: +To run the server, please execute the following from the root directory: ``` -sudo pip3 install -U connexion flask_testing # install Connexion from PyPI -python3 app.py +pip3 install -r requirements.txt +python3 -m swagger_server ``` and open your browser to here: @@ -26,3 +26,8 @@ Your Swagger definition lives here: http://localhost:8080/v2/swagger.json ``` +To launch the integration tests, use tox: +``` +sudo pip install tox +tox +``` diff --git a/samples/server/petstore/flaskConnexion/app.py b/samples/server/petstore/flaskConnexion/app.py deleted file mode 100644 index c5342f15859..00000000000 --- a/samples/server/petstore/flaskConnexion/app.py +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env python3 - -import connexion -from connexion.decorators import produces -from six import iteritems -from models.base_model_ import Model - - -class JSONEncoder(produces.JSONEncoder): - include_nulls = False - - def default(self, o): - if isinstance(o, Model): - dikt = {} - for attr, _ in iteritems(o.swagger_types): - value = getattr(o, attr) - if value is None and not self.include_nulls: - continue - attr = o.attribute_map[attr] - dikt[attr] = value - return dikt - return produces.JSONEncoder.default(self, o) - - -if __name__ == '__main__': - app = connexion.App(__name__, specification_dir='./swagger/') - app.app.json_encoder = JSONEncoder - app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) - app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion/git_push.sh b/samples/server/petstore/flaskConnexion/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/server/petstore/flaskConnexion/requirements.txt b/samples/server/petstore/flaskConnexion/requirements.txt new file mode 100644 index 00000000000..995dc64d655 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/requirements.txt @@ -0,0 +1,3 @@ +connexion == 1.0.129 +python_dateutil == 2.6.0 +setuptools >= 21.0.0 diff --git a/samples/server/petstore/flaskConnexion/setup.py b/samples/server/petstore/flaskConnexion/setup.py new file mode 100644 index 00000000000..7a1ce575d35 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/setup.py @@ -0,0 +1,33 @@ +# coding: utf-8 + +import sys +from setuptools import setup, find_packages + +NAME = "swagger_server" +VERSION = "1.0.0" + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["connexion"] + +setup( + name=NAME, + version=VERSION, + description="Swagger Petstore", + author_email="apiteam@swagger.io", + url="", + keywords=["Swagger", "Swagger Petstore"], + install_requires=REQUIRES, + packages=find_packages(), + package_data={'': ['swagger/swagger.yaml']}, + include_package_data=True, + long_description="""\ + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + """ +) + diff --git a/samples/server/petstore/flaskConnexion/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion/__init__.py rename to samples/server/petstore/flaskConnexion/swagger_server/__init__.py diff --git a/samples/server/petstore/flaskConnexion/swagger_server/__main__.py b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py new file mode 100644 index 00000000000..b0d689211d2 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/swagger_server/__main__.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python3 + +import connexion +from .encoder import JSONEncoder + + +if __name__ == '__main__': + app = connexion.App(__name__, specification_dir='./swagger/') + app.app.json_encoder = JSONEncoder + app.add_api('swagger.yaml', arguments={'title': 'This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.'}) + app.run(port=8080) diff --git a/samples/server/petstore/flaskConnexion/controllers/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion/controllers/__init__.py rename to samples/server/petstore/flaskConnexion/swagger_server/controllers/__init__.py diff --git a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py similarity index 93% rename from samples/server/petstore/flaskConnexion/controllers/pet_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py index 0a1be8f8863..5a999aae88f 100644 --- a/samples/server/petstore/flaskConnexion/controllers/pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/pet_controller.py @@ -1,10 +1,10 @@ import connexion -from models.api_response import ApiResponse -from models.pet import Pet +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.pet import Pet from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def add_pet(body): diff --git a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py similarity index 92% rename from samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py index 5373cbf5f71..0cdcaf445dc 100644 --- a/samples/server/petstore/flaskConnexion-python2/controllers/store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/store_controller.py @@ -1,9 +1,9 @@ import connexion -from models.order import Order +from swagger_server.models.order import Order from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def delete_order(orderId): diff --git a/samples/server/petstore/flaskConnexion/controllers/user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py similarity index 95% rename from samples/server/petstore/flaskConnexion/controllers/user_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py index 0e406488a7f..9a88626c5b8 100644 --- a/samples/server/petstore/flaskConnexion/controllers/user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/controllers/user_controller.py @@ -1,9 +1,9 @@ import connexion -from models.user import User +from swagger_server.models.user import User from datetime import date, datetime from typing import List, Dict from six import iteritems -from util import deserialize_date, deserialize_datetime +from ..util import deserialize_date, deserialize_datetime def create_user(body): diff --git a/samples/server/petstore/flaskConnexion/swagger_server/encoder.py b/samples/server/petstore/flaskConnexion/swagger_server/encoder.py new file mode 100644 index 00000000000..90988e4d3ea --- /dev/null +++ b/samples/server/petstore/flaskConnexion/swagger_server/encoder.py @@ -0,0 +1,19 @@ +from connexion.decorators import produces +from six import iteritems +from swagger_server.models.base_model_ import Model + + +class JSONEncoder(produces.JSONEncoder): + include_nulls = False + + def default(self, o): + if isinstance(o, Model): + dikt = {} + for attr, _ in iteritems(o.swagger_types): + value = getattr(o, attr) + if value is None and not self.include_nulls: + continue + attr = o.attribute_map[attr] + dikt[attr] = value + return dikt + return produces.JSONEncoder.default(self, o) \ No newline at end of file diff --git a/samples/server/petstore/flaskConnexion/models/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py similarity index 100% rename from samples/server/petstore/flaskConnexion/models/__init__.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/__init__.py diff --git a/samples/server/petstore/flaskConnexion/models/api_response.py b/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py similarity index 98% rename from samples/server/petstore/flaskConnexion/models/api_response.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py index 607a47e4dd4..b49738579d6 100644 --- a/samples/server/petstore/flaskConnexion/models/api_response.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/api_response.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class ApiResponse(Model): diff --git a/samples/server/petstore/flaskConnexion/models/base_model_.py b/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py similarity index 98% rename from samples/server/petstore/flaskConnexion/models/base_model_.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py index d10efa4f2c6..5202b30fb63 100644 --- a/samples/server/petstore/flaskConnexion/models/base_model_.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/base_model_.py @@ -1,7 +1,7 @@ from pprint import pformat from typing import TypeVar, Type from six import iteritems -from util import deserialize_model +from ..util import deserialize_model T = TypeVar('T') diff --git a/samples/server/petstore/flaskConnexion/models/category.py b/samples/server/petstore/flaskConnexion/swagger_server/models/category.py similarity index 98% rename from samples/server/petstore/flaskConnexion/models/category.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/category.py index e36ffb3bffa..ba381b5792f 100644 --- a/samples/server/petstore/flaskConnexion/models/category.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/category.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Category(Model): diff --git a/samples/server/petstore/flaskConnexion/models/order.py b/samples/server/petstore/flaskConnexion/swagger_server/models/order.py similarity index 99% rename from samples/server/petstore/flaskConnexion/models/order.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/order.py index 1b4ad9f849d..772769084d5 100644 --- a/samples/server/petstore/flaskConnexion/models/order.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/order.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Order(Model): diff --git a/samples/server/petstore/flaskConnexion/models/pet.py b/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py similarity index 97% rename from samples/server/petstore/flaskConnexion/models/pet.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/pet.py index 11ad67f7649..6594f0f90d2 100644 --- a/samples/server/petstore/flaskConnexion/models/pet.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/pet.py @@ -1,12 +1,12 @@ # coding: utf-8 from __future__ import absolute_import -from models.category import Category -from models.tag import Tag +from swagger_server.models.category import Category +from swagger_server.models.tag import Tag from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Pet(Model): diff --git a/samples/server/petstore/flaskConnexion/models/tag.py b/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py similarity index 97% rename from samples/server/petstore/flaskConnexion/models/tag.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/tag.py index 41f1b024fe8..635ab029eea 100644 --- a/samples/server/petstore/flaskConnexion/models/tag.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/tag.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class Tag(Model): diff --git a/samples/server/petstore/flaskConnexion/models/user.py b/samples/server/petstore/flaskConnexion/swagger_server/models/user.py similarity index 99% rename from samples/server/petstore/flaskConnexion/models/user.py rename to samples/server/petstore/flaskConnexion/swagger_server/models/user.py index 77fdaa7a252..08ebe6cf9db 100644 --- a/samples/server/petstore/flaskConnexion/models/user.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/models/user.py @@ -4,7 +4,7 @@ from __future__ import absolute_import from .base_model_ import Model from datetime import date, datetime from typing import List, Dict -from util import deserialize_model +from ..util import deserialize_model class User(Model): diff --git a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml b/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml similarity index 91% rename from samples/server/petstore/flaskConnexion/swagger/swagger.yaml rename to samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml index 3d22ab2d847..9d948b2124f 100644 --- a/samples/server/petstore/flaskConnexion/swagger/swagger.yaml +++ b/samples/server/petstore/flaskConnexion/swagger_server/swagger/swagger.yaml @@ -58,7 +58,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" put: tags: - "pet" @@ -89,7 +89,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/findByStatus: get: tags: @@ -127,7 +127,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/findByTags: get: tags: @@ -161,7 +161,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/{petId}: get: tags: @@ -190,7 +190,7 @@ paths: description: "Pet not found" security: - api_key: [] - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" post: tags: - "pet" @@ -226,7 +226,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" delete: tags: - "pet" @@ -254,7 +254,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /pet/{petId}/uploadImage: post: tags: @@ -292,7 +292,7 @@ paths: - petstore_auth: - "write:pets" - "read:pets" - x-swagger-router-controller: "controllers.pet_controller" + x-swagger-router-controller: "swagger_server.controllers.pet_controller" /store/inventory: get: tags: @@ -313,7 +313,7 @@ paths: format: "int32" security: - api_key: [] - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /store/order: post: tags: @@ -338,7 +338,7 @@ paths: $ref: "#/definitions/Order" 400: description: "Invalid Order" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /store/order/{orderId}: get: tags: @@ -368,7 +368,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" delete: tags: - "store" @@ -391,7 +391,7 @@ paths: description: "Invalid ID supplied" 404: description: "Order not found" - x-swagger-router-controller: "controllers.store_controller" + x-swagger-router-controller: "swagger_server.controllers.store_controller" /user: post: tags: @@ -412,7 +412,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/createWithArray: post: tags: @@ -435,7 +435,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/createWithList: post: tags: @@ -458,7 +458,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/login: get: tags: @@ -496,7 +496,7 @@ paths: description: "date in UTC when toekn expires" 400: description: "Invalid username/password supplied" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/logout: get: tags: @@ -511,7 +511,7 @@ paths: responses: default: description: "successful operation" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" /user/{username}: get: tags: @@ -537,7 +537,7 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" put: tags: - "user" @@ -564,7 +564,7 @@ paths: description: "Invalid user supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" delete: tags: - "user" @@ -585,7 +585,7 @@ paths: description: "Invalid username supplied" 404: description: "User not found" - x-swagger-router-controller: "controllers.user_controller" + x-swagger-router-controller: "swagger_server.controllers.user_controller" securityDefinitions: petstore_auth: type: "oauth2" diff --git a/samples/server/petstore/flaskConnexion/test/__init__.py b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py similarity index 91% rename from samples/server/petstore/flaskConnexion/test/__init__.py rename to samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py index 352991098f1..77b10c3a012 100644 --- a/samples/server/petstore/flaskConnexion/test/__init__.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/__init__.py @@ -1,5 +1,5 @@ from flask_testing import TestCase -from app import JSONEncoder +from ..encoder import JSONEncoder import connexion import logging diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py similarity index 97% rename from samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py index 31e3b3fcb6b..b99269a991a 100644 --- a/samples/server/petstore/flaskConnexion-python2/test/test_pet_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_pet_controller.py @@ -2,8 +2,8 @@ from __future__ import absolute_import -from models.api_response import ApiResponse -from models.pet import Pet +from swagger_server.models.api_response import ApiResponse +from swagger_server.models.pet import Pet from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py similarity index 97% rename from samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py index 33a007ae195..0a5360b4e25 100644 --- a/samples/server/petstore/flaskConnexion-python2/test/test_store_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_store_controller.py @@ -2,7 +2,7 @@ from __future__ import absolute_import -from models.order import Order +from swagger_server.models.order import Order from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion/test/test_user_controller.py b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py similarity index 98% rename from samples/server/petstore/flaskConnexion/test/test_user_controller.py rename to samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py index 52dacf3df32..867de3c0150 100644 --- a/samples/server/petstore/flaskConnexion/test/test_user_controller.py +++ b/samples/server/petstore/flaskConnexion/swagger_server/test/test_user_controller.py @@ -2,7 +2,7 @@ from __future__ import absolute_import -from models.user import User +from swagger_server.models.user import User from . import BaseTestCase from six import BytesIO from flask import json diff --git a/samples/server/petstore/flaskConnexion/util.py b/samples/server/petstore/flaskConnexion/swagger_server/util.py similarity index 100% rename from samples/server/petstore/flaskConnexion/util.py rename to samples/server/petstore/flaskConnexion/swagger_server/util.py diff --git a/samples/server/petstore/flaskConnexion/test-requirements.txt b/samples/server/petstore/flaskConnexion/test-requirements.txt new file mode 100644 index 00000000000..7f8d96e6b40 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/test-requirements.txt @@ -0,0 +1,6 @@ +flask_testing==0.6.1 +coverage>=4.0.3 +nose>=1.3.7 +pluggy>=0.3.1 +py>=1.4.31 +randomize>=0.13 diff --git a/samples/server/petstore/flaskConnexion/tox.ini b/samples/server/petstore/flaskConnexion/tox.ini new file mode 100644 index 00000000000..b696749b3a1 --- /dev/null +++ b/samples/server/petstore/flaskConnexion/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py35 + +[testenv] +deps=-r{toxinidir}/requirements.txt + -r{toxinidir}/test-requirements.txt + +commands= + nosetests \ + [] \ No newline at end of file From c15743bfe6d5d9ad99d493adf189961dd2c69039 Mon Sep 17 00:00:00 2001 From: Daniel Date: Thu, 24 Nov 2016 17:14:59 +0100 Subject: [PATCH 104/269] Issue4254 (#4255) * Issue 4254 - Added mechanism for cache bursting * Issue 4254 - Updated petstore samples --- .../src/main/resources/Javascript/ApiClient.mustache | 11 +++++++++++ .../petstore/javascript-promise/src/ApiClient.js | 11 +++++++++++ samples/client/petstore/javascript/src/ApiClient.js | 11 +++++++++++ 3 files changed, 33 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index 3cb405b6d71..164f11d4747 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -67,6 +67,14 @@ * @default 60000 */ this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; }; {{#emitJSDoc}} /** @@ -353,6 +361,9 @@ this.applyAuthToRequest(request, authNames); // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } request.query(this.normalizeParams(queryParams)); // set header parameters diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 25cb11e4d73..c0b5441412c 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -70,6 +70,14 @@ * @default 60000 */ this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; }; /** @@ -347,6 +355,9 @@ this.applyAuthToRequest(request, authNames); // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } request.query(this.normalizeParams(queryParams)); // set header parameters diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index cf3fe731cf6..54b1f806af6 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -70,6 +70,14 @@ * @default 60000 */ this.timeout = 60000; + + /** + * If set to false an additional timestamp parameter is added to all API GET calls to + * prevent browser caching + * @type {Boolean} + * @default true + */ + this.cache = true; }; /** @@ -356,6 +364,9 @@ this.applyAuthToRequest(request, authNames); // set query parameters + if (httpMethod.toUpperCase() === 'GET' && this.cache === false) { + queryParams['_'] = new Date().getTime(); + } request.query(this.normalizeParams(queryParams)); // set header parameters From 1ea9865a4498e26bb1f4ecf490aaad19d19357a8 Mon Sep 17 00:00:00 2001 From: Robert Biehl Date: Fri, 25 Nov 2016 09:12:41 +0100 Subject: [PATCH 105/269] [PHP] Fix discriminator handling (#4246) * [PHP] Fix discriminator handling * [PHP] Fix discriminator handling (Update examples) --- .../resources/php/ObjectSerializer.mustache | 9 ++-- .../src/main/resources/php/api.mustache | 2 +- .../main/resources/php/model_generic.mustache | 8 +-- .../php/SwaggerClient-php/.php_cs | 18 +++++++ .../php/SwaggerClient-php/.travis.yml | 2 +- .../php/SwaggerClient-php/README.md | 19 ++++--- .../php/SwaggerClient-php/composer.json | 5 +- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 22 ++++---- .../php/SwaggerClient-php/lib/ApiClient.php | 44 ++++++++------- .../SwaggerClient-php/lib/Configuration.php | 19 ++++--- .../lib/Model/ModelReturn.php | 53 ++++++++++--------- .../lib/ObjectSerializer.php | 44 +++++++-------- .../php/SwaggerClient-php/phpunit.xml.dist | 21 ++++++++ .../lib/Model/AdditionalPropertiesClass.php | 2 + .../SwaggerClient-php/lib/Model/Animal.php | 6 ++- .../lib/Model/AnimalFarm.php | 2 + .../lib/Model/ApiResponse.php | 2 + .../lib/Model/ArrayOfArrayOfNumberOnly.php | 2 + .../lib/Model/ArrayOfNumberOnly.php | 2 + .../SwaggerClient-php/lib/Model/ArrayTest.php | 2 + .../php/SwaggerClient-php/lib/Model/Cat.php | 2 + .../SwaggerClient-php/lib/Model/Category.php | 2 + .../SwaggerClient-php/lib/Model/Client.php | 2 + .../php/SwaggerClient-php/lib/Model/Dog.php | 2 + .../lib/Model/EnumArrays.php | 2 + .../SwaggerClient-php/lib/Model/EnumTest.php | 2 + .../lib/Model/FormatTest.php | 2 + .../lib/Model/HasOnlyReadOnly.php | 2 + .../SwaggerClient-php/lib/Model/MapTest.php | 2 + ...PropertiesAndAdditionalPropertiesClass.php | 2 + .../lib/Model/Model200Response.php | 2 + .../SwaggerClient-php/lib/Model/ModelList.php | 2 + .../lib/Model/ModelReturn.php | 2 + .../php/SwaggerClient-php/lib/Model/Name.php | 2 + .../lib/Model/NumberOnly.php | 2 + .../php/SwaggerClient-php/lib/Model/Order.php | 2 + .../php/SwaggerClient-php/lib/Model/Pet.php | 2 + .../lib/Model/ReadOnlyFirst.php | 2 + .../lib/Model/SpecialModelName.php | 2 + .../php/SwaggerClient-php/lib/Model/Tag.php | 2 + .../php/SwaggerClient-php/lib/Model/User.php | 2 + .../lib/ObjectSerializer.php | 9 ++-- 42 files changed, 216 insertions(+), 119 deletions(-) create mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/.php_cs create mode 100644 samples/client/petstore-security-test/php/SwaggerClient-php/phpunit.xml.dist diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index e89dd01d51e..9550de6d193 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -204,7 +204,7 @@ class ObjectSerializer * * @return object|array|null an single or an array of $class instances */ - public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) + public static function deserialize($data, $class, $httpHeaders = null) { if (null === $data) { return null; @@ -215,7 +215,7 @@ class ObjectSerializer $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass, null, $discriminator); + $deserialized[$key] = self::deserialize($value, $subClass, null); } } return $deserialized; @@ -223,7 +223,7 @@ class ObjectSerializer $subClass = substr($class, 0, -2); $values = []; foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass, null, $discriminator); + $values[] = self::deserialize($value, $subClass, null); } return $values; } elseif ($class === 'object') { @@ -261,6 +261,7 @@ class ObjectSerializer return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { $subclass = '\{{invokerPackage}}\Model\\' . $data->{$discriminator}; if (is_subclass_of($subclass, $class)) { @@ -277,7 +278,7 @@ class ObjectSerializer $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); } } return $instance; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 2148d1ea9ad..1768ff7ac5e 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -284,7 +284,7 @@ use \{{invokerPackage}}\ObjectSerializer; ); {{#returnType}} - return [$this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader{{#discriminator}}, '{{discriminator}}'{{/discriminator}}), $statusCode, $httpHeader]; + return [$this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader), $statusCode, $httpHeader]; {{/returnType}} {{^returnType}} return [null, $statusCode, $httpHeader]; diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index 1e221b78377..f7ab60ad616 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -1,5 +1,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}implements ArrayAccess { + const DISCRIMINATOR = {{#discriminator}}'{{discriminator}}'{{/discriminator}}{{^discriminator}}null{{/discriminator}}; + /** * The original name of the model. * @var string @@ -103,8 +105,8 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{#discriminator}} // Initialize discriminator property with the model name. - $discrimintor = array_search('{{discriminator}}', self::$attributeMap); - $this->container[$discrimintor] = static::$swaggerModelName; + $discriminator = array_search('{{discriminator}}', self::$attributeMap); + $this->container[$discriminator] = static::$swaggerModelName; {{/discriminator}} } @@ -370,4 +372,4 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple return json_encode(\{{invokerPackage}}\ObjectSerializer::sanitizeForSerialization($this)); } -} \ No newline at end of file +} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/.php_cs b/samples/client/petstore-security-test/php/SwaggerClient-php/.php_cs new file mode 100644 index 00000000000..6b8e23c818a --- /dev/null +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/.php_cs @@ -0,0 +1,18 @@ +level(Symfony\CS\FixerInterface::PSR2_LEVEL) + ->setUsingCache(true) + ->fixers( + [ + 'ordered_use', + 'phpdoc_order', + 'short_array_syntax', + 'strict', + 'strict_param' + ] + ) + ->finder( + Symfony\CS\Finder\DefaultFinder::create() + ->in(__DIR__) + ); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/.travis.yml b/samples/client/petstore-security-test/php/SwaggerClient-php/.travis.yml index 3c97d942552..d77f3825f6f 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/.travis.yml +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/.travis.yml @@ -7,4 +7,4 @@ php: - 7.0 - hhvm before_install: "composer install" -script: "phpunit lib/Tests" +script: "vendor/bin/phpunit" diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index baa8eb42188..e25623732e0 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -4,7 +4,6 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r -- Build date: 2016-08-05T11:24:40.650+02:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -46,7 +45,7 @@ To run the unit tests: ``` composer install -./vendor/bin/phpunit lib/Tests +./vendor/bin/phpunit ``` ## Getting Started @@ -86,20 +85,20 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - **write:pets**: modify pets in your account */ ' " =end -- \r\n \n \r - - **read:pets**: read your pets */ ' " =end -- \r\n \n \r - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key */ ' " =end -- \r\n \n \r -- **Location**: HTTP header + - **write:pets**: modify pets in your account *_/ ' \" =end -- \\r\\n \\n \\r + - **read:pets**: read your pets *_/ ' \" =end -- \\r\\n \\n \\r ## Author diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index b9290bdacb9..78602f3be45 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -8,7 +8,7 @@ "api" ], "homepage": "http://swagger.io", - "license": "Apache v2", + "license": "Apache-2.0", "authors": [ { "name": "Swagger and contributors", @@ -24,7 +24,8 @@ "require-dev": { "phpunit/phpunit": "~4.8", "satooshi/php-coveralls": "~1.0", - "squizlabs/php_codesniffer": "~2.6" + "squizlabs/php_codesniffer": "~2.6", + "friendsofphp/php-cs-fixer": "~1.12" }, "autoload": { "psr-4": { "Swagger\\Client\\" : "lib/" } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index 5ce09b9a7ec..d399e789de5 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -40,9 +40,9 @@ namespace Swagger\Client\Api; -use \Swagger\Client\Configuration; use \Swagger\Client\ApiClient; use \Swagger\Client\ApiException; +use \Swagger\Client\Configuration; use \Swagger\Client\ObjectSerializer; /** @@ -56,7 +56,6 @@ use \Swagger\Client\ObjectSerializer; */ class FakeApi { - /** * API Client * @@ -71,7 +70,7 @@ class FakeApi */ public function __construct(\Swagger\Client\ApiClient $apiClient = null) { - if ($apiClient == null) { + if ($apiClient === null) { $apiClient = new ApiClient(); $apiClient->getConfig()->setHost('https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'); } @@ -108,8 +107,8 @@ class FakeApi * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * * @param string $test_code_inject____end____rn_n_r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @return void * @throws \Swagger\Client\ApiException on non-2xx response + * @return void */ public function testCodeInjectEndRnNR($test_code_inject____end____rn_n_r = null) { @@ -123,22 +122,22 @@ class FakeApi * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * * @param string $test_code_inject____end____rn_n_r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response + * @return array of null, HTTP status code, HTTP response headers (array of strings) */ public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end____rn_n_r = null) { // parse inputs $resourcePath = "/fake"; $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*_/ \" =end --')); + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json', '*_/ \" =end --']); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*_/ \" =end --')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json', '*_/ \" =end --']); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -166,7 +165,7 @@ class FakeApi '/fake' ); - return array(null, $statusCode, $httpHeader); + return [null, $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { } @@ -174,5 +173,4 @@ class FakeApi throw $e; } } - } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index 5f774a834d3..c8d7f70fedb 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -52,7 +52,6 @@ namespace Swagger\Client; */ class ApiClient { - public static $PATCH = "PATCH"; public static $POST = "POST"; public static $GET = "GET"; @@ -82,7 +81,7 @@ class ApiClient */ public function __construct(\Swagger\Client\Configuration $config = null) { - if ($config == null) { + if ($config === null) { $config = Configuration::getDefaultConfiguration(); } @@ -151,8 +150,7 @@ class ApiClient */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType = null, $endpointPath = null) { - - $headers = array(); + $headers = []; // construct the http header $headerParams = array_merge( @@ -165,9 +163,9 @@ class ApiClient } // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { + if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers, true)) { $postData = http_build_query($postData); - } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model + } elseif ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers, true)) { // json model $postData = json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($postData)); } @@ -175,7 +173,7 @@ class ApiClient $curl = curl_init(); // set timeout, if needed - if ($this->config->getCurlTimeout() != 0) { + if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } // return the result on success, rather than just true @@ -184,7 +182,7 @@ class ApiClient curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // disable SSL verification, if needed - if ($this->config->getSSLVerification() == false) { + if ($this->config->getSSLVerification() === false) { curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } @@ -193,24 +191,24 @@ class ApiClient $url = ($url . '?' . http_build_query($queryParams)); } - if ($method == self::$POST) { + if ($method === self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$HEAD) { + } elseif ($method === self::$HEAD) { curl_setopt($curl, CURLOPT_NOBODY, true); - } elseif ($method == self::$OPTIONS) { + } elseif ($method === self::$OPTIONS) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PATCH) { + } elseif ($method === self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$PUT) { + } elseif ($method === self::$PUT) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method == self::$DELETE) { + } elseif ($method === self::$DELETE) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } elseif ($method != self::$GET) { + } elseif ($method !== self::$GET) { throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); @@ -244,7 +242,7 @@ class ApiClient } // Handle the response - if ($response_info['http_code'] == 0) { + if ($response_info['http_code'] === 0) { $curl_error_message = curl_error($curl); // curl_exec can sometimes fail but still return a blank message from curl_error(). @@ -260,8 +258,8 @@ class ApiClient throw $exception; } elseif ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299) { // return raw body if response is a file - if ($responseType == '\SplFileObject' || $responseType == 'string') { - return array($http_body, $response_info['http_code'], $http_header); + if ($responseType === '\SplFileObject' || $responseType === 'string') { + return [$http_body, $response_info['http_code'], $http_header]; } $data = json_decode($http_body); @@ -281,7 +279,7 @@ class ApiClient $data ); } - return array($data, $response_info['http_code'], $http_header); + return [$data, $response_info['http_code'], $http_header]; } /** @@ -330,7 +328,7 @@ class ApiClient protected function httpParseHeaders($raw_headers) { // ref/credit: http://php.net/manual/en/function.http-parse-headers.php#112986 - $headers = array(); + $headers = []; $key = ''; foreach (explode("\n", $raw_headers) as $h) { @@ -340,14 +338,14 @@ class ApiClient if (!isset($headers[$h[0]])) { $headers[$h[0]] = trim($h[1]); } elseif (is_array($headers[$h[0]])) { - $headers[$h[0]] = array_merge($headers[$h[0]], array(trim($h[1]))); + $headers[$h[0]] = array_merge($headers[$h[0]], [trim($h[1])]); } else { - $headers[$h[0]] = array_merge(array($headers[$h[0]]), array(trim($h[1]))); + $headers[$h[0]] = array_merge([$headers[$h[0]]], [trim($h[1])]); } $key = $h[0]; } else { - if (substr($h[0], 0, 1) == "\t") { + if (substr($h[0], 0, 1) === "\t") { $headers[$key] .= "\r\n\t".trim($h[0]); } elseif (!$key) { $headers[0] = trim($h[0]); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 12c2b9b0ea2..69c7ce6bcbd 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -52,7 +52,6 @@ namespace Swagger\Client; */ class Configuration { - private static $defaultConfiguration = null; /** @@ -60,14 +59,14 @@ class Configuration * * @var string[] */ - protected $apiKeys = array(); + protected $apiKeys = []; /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ - protected $apiKeyPrefixes = array(); + protected $apiKeyPrefixes = []; /** * Access token for OAuth @@ -91,11 +90,11 @@ class Configuration protected $password = ''; /** - * The default instance of ApiClient + * The default header(s) * - * @var \Swagger\Client\ApiClient + * @var array */ - protected $defaultHeaders = array(); + protected $defaultHeaders = []; /** * The host @@ -283,7 +282,7 @@ class Configuration * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) * - * @return ApiClient + * @return Configuration */ public function addDefaultHeader($headerName, $headerValue) { @@ -345,7 +344,7 @@ class Configuration * * @param string $userAgent the user agent of the api client * - * @return ApiClient + * @return Configuration */ public function setUserAgent($userAgent) { @@ -372,7 +371,7 @@ class Configuration * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] * - * @return ApiClient + * @return Configuration */ public function setCurlTimeout($seconds) { @@ -493,7 +492,7 @@ class Configuration */ public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { + if (self::$defaultConfiguration === null) { self::$defaultConfiguration = new Configuration(); } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php index c4baed23baa..2eade42511f 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -48,7 +48,7 @@ use \ArrayAccess; * * @category Class */ // @description Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r -/** +/** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 @@ -56,6 +56,8 @@ use \ArrayAccess; */ class ModelReturn implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string @@ -66,9 +68,9 @@ class ModelReturn implements ArrayAccess * Array of property to type mappings. Used for (de)serialization * @var string[] */ - protected static $swaggerTypes = array( + protected static $swaggerTypes = [ 'return' => 'int' - ); + ]; public static function swaggerTypes() { @@ -79,36 +81,38 @@ class ModelReturn implements ArrayAccess * Array of attributes where the key is the local name, and the value is the original name * @var string[] */ - protected static $attributeMap = array( + protected static $attributeMap = [ 'return' => 'return' - ); + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'return' => 'setReturn' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'return' => 'getReturn' + ]; public static function attributeMap() { return self::$attributeMap; } - /** - * Array of attributes to setter functions (for deserialization of responses) - * @var string[] - */ - protected static $setters = array( - 'return' => 'setReturn' - ); - public static function setters() { return self::$setters; } - /** - * Array of attributes to getter functions (for serialization of requests) - * @var string[] - */ - protected static $getters = array( - 'return' => 'getReturn' - ); - public static function getters() { return self::$getters; @@ -122,11 +126,11 @@ class ModelReturn implements ArrayAccess * Associative array for storing property values * @var mixed[] */ - protected $container = array(); + protected $container = []; /** * Constructor - * @param mixed[] $data Associated array of property value initalizing the model + * @param mixed[] $data Associated array of property values initializing the model */ public function __construct(array $data = null) { @@ -140,7 +144,7 @@ class ModelReturn implements ArrayAccess */ public function listInvalidProperties() { - $invalid_properties = array(); + $invalid_properties = []; return $invalid_properties; } @@ -235,4 +239,3 @@ class ModelReturn implements ArrayAccess } } - diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index f5ce9361286..c72c36f24fd 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -52,13 +52,12 @@ namespace Swagger\Client; */ class ObjectSerializer { - /** * Serialize data * * @param mixed $data the data to serialize * - * @return string serialized form of $data + * @return string|object serialized form of $data */ public static function sanitizeForSerialization($data) { @@ -72,7 +71,7 @@ class ObjectSerializer } return $data; } elseif (is_object($data)) { - $values = array(); + $values = []; foreach (array_keys($data::swaggerTypes()) as $property) { $getter = $data::getters()[$property]; if ($data->$getter() !== null) { @@ -121,7 +120,7 @@ class ObjectSerializer * If it's a string, pass through unchanged. It will be url-encoded * later. * - * @param object $object an object to be serialized to a string + * @param string[]|string|\DateTime $object an object to be serialized to a string * * @return string the serialized object */ @@ -153,7 +152,7 @@ class ObjectSerializer * the http body (form parameter). If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the form parameter + * @param string|\SplFileObject $value the value of the form parameter * * @return string the form string */ @@ -171,7 +170,7 @@ class ObjectSerializer * the parameter. If it's a string, pass through unchanged * If it's a datetime object, format it in ISO8601 * - * @param string $value the value of the parameter + * @param string|\DateTime $value the value of the parameter * * @return string the header string */ @@ -187,9 +186,10 @@ class ObjectSerializer /** * Serialize an array to a string. * - * @param array $collection collection to serialize to a string - * @param string $collectionFormat the format use for serialization (csv, + * @param array $collection collection to serialize to a string + * @param string $collectionFormat the format use for serialization (csv, * ssv, tsv, pipes, multi) + * @param bool $allowCollectionFormatMulti allow collection format to be a multidimensional array * * @return string */ @@ -220,33 +220,33 @@ class ObjectSerializer /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string - * @param string $httpHeaders HTTP headers - * @param string $discriminator discriminator if polymorphism is used + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string[] $httpHeaders HTTP headers + * @param string $discriminator discriminator if polymorphism is used * - * @return object an instance of $class + * @return object|array|null an single or an array of $class instances */ - public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) + public static function deserialize($data, $class, $httpHeaders = null) { if (null === $data) { return null; } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); - $deserialized = array(); + $deserialized = []; if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass, null, $discriminator); + $deserialized[$key] = self::deserialize($value, $subClass, null); } } return $deserialized; - } elseif (strcasecmp(substr($class, -2), '[]') == 0) { + } elseif (strcasecmp(substr($class, -2), '[]') === 0) { $subClass = substr($class, 0, -2); - $values = array(); + $values = []; foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass, null, $discriminator); + $values[] = self::deserialize($value, $subClass, null); } return $values; } elseif ($class === 'object') { @@ -264,7 +264,7 @@ class ObjectSerializer } else { return null; } - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, ['DateTime', 'bool', 'boolean', 'byte', 'double', 'float', 'int', 'integer', 'mixed', 'number', 'object', 'string', 'void'], true)) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { @@ -277,7 +277,6 @@ class ObjectSerializer } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - if (Configuration::getDefaultConfiguration()->getDebug()) { error_log("[DEBUG] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.".PHP_EOL, 3, Configuration::getDefaultConfiguration()->getDebugFile()); } @@ -285,6 +284,7 @@ class ObjectSerializer return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { $subclass = '\Swagger\Client\Model\\' . $data->{$discriminator}; if (is_subclass_of($subclass, $class)) { @@ -301,7 +301,7 @@ class ObjectSerializer $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); } } return $instance; diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/phpunit.xml.dist b/samples/client/petstore-security-test/php/SwaggerClient-php/phpunit.xml.dist new file mode 100644 index 00000000000..c12ee148477 --- /dev/null +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/phpunit.xml.dist @@ -0,0 +1,21 @@ + + + + + ./test/Api + ./test/Model + + + + + + ./lib/Api + ./lib/Model + + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 0cbdb8b1220..60c0799ecc3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class AdditionalPropertiesClass implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 9344dd618f7..06625475509 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Animal implements ArrayAccess { + const DISCRIMINATOR = 'className'; + /** * The original name of the model. * @var string @@ -126,8 +128,8 @@ class Animal implements ArrayAccess $this->container['color'] = isset($data['color']) ? $data['color'] : 'red'; // Initialize discriminator property with the model name. - $discrimintor = array_search('className', self::$attributeMap); - $this->container[$discrimintor] = static::$swaggerModelName; + $discriminator = array_search('className', self::$attributeMap); + $this->container[$discriminator] = static::$swaggerModelName; } /** diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index 185f7b2e772..a814b227c14 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class AnimalFarm implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index dd78695f4ae..1240d1f3efb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ApiResponse implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index f21da5a742d..060c16dc443 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ArrayOfArrayOfNumberOnly implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index d9b64bbe0ae..eac1a959200 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ArrayOfNumberOnly implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index be4bc7b0231..e3266c65b0c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ArrayTest implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index fdaa49e31f8..fbab168ade9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Cat extends Animal implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 1258907ffec..b3f6ffc1c7c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Category implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php index 558469ed5db..55ef2a1918a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Client implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 898e96f5373..2888805e717 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Dog extends Animal implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index 548de3b160f..c2bc15def85 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class EnumArrays implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index dcfd407d690..b0ba03e5748 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class EnumTest implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 39fc6cf385a..72c8f79a357 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class FormatTest implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index 75520744546..6251620638f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class HasOnlyReadOnly implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index ee1dfc365b8..986d9b1d81a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class MapTest implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 7c8801f342b..8af27a9c528 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 1e0117d85fe..d1d79f9fd6c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -43,6 +43,8 @@ use \ArrayAccess; */ class Model200Response implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php index 092b3e51db3..d185af146f4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ModelList implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 2723f3869b5..379acc123a6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -43,6 +43,8 @@ use \ArrayAccess; */ class ModelReturn implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index ab38479e880..9722713dc26 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -43,6 +43,8 @@ use \ArrayAccess; */ class Name implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index bb57967f248..3603f9bdd9f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class NumberOnly implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 096af928d31..a50b997b635 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Order implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 1b05883874d..fe9f255f75c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Pet implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index 47efccc34b5..838792fa0c1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class ReadOnlyFirst implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index 514073dbb09..ad2e8394bc7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class SpecialModelName implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index d6d2fb62f2c..29578f37802 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class Tag implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index a69ea12f254..ca36471adce 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -42,6 +42,8 @@ use \ArrayAccess; */ class User implements ArrayAccess { + const DISCRIMINATOR = null; + /** * The original name of the model. * @var string diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 9ba48f42977..fbb2e8b1e45 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -214,7 +214,7 @@ class ObjectSerializer * * @return object|array|null an single or an array of $class instances */ - public static function deserialize($data, $class, $httpHeaders = null, $discriminator = null) + public static function deserialize($data, $class, $httpHeaders = null) { if (null === $data) { return null; @@ -225,7 +225,7 @@ class ObjectSerializer $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $deserialized[$key] = self::deserialize($value, $subClass, null, $discriminator); + $deserialized[$key] = self::deserialize($value, $subClass, null); } } return $deserialized; @@ -233,7 +233,7 @@ class ObjectSerializer $subClass = substr($class, 0, -2); $values = []; foreach ($data as $key => $value) { - $values[] = self::deserialize($value, $subClass, null, $discriminator); + $values[] = self::deserialize($value, $subClass, null); } return $values; } elseif ($class === 'object') { @@ -271,6 +271,7 @@ class ObjectSerializer return $deserialized; } else { // If a discriminator is defined and points to a valid subclass, use it. + $discriminator = $class::DISCRIMINATOR; if (!empty($discriminator) && isset($data->{$discriminator}) && is_string($data->{$discriminator})) { $subclass = '\Swagger\Client\Model\\' . $data->{$discriminator}; if (is_subclass_of($subclass, $class)) { @@ -287,7 +288,7 @@ class ObjectSerializer $propertyValue = $data->{$instance::attributeMap()[$property]}; if (isset($propertyValue)) { - $instance->$propertySetter(self::deserialize($propertyValue, $type, null, $discriminator)); + $instance->$propertySetter(self::deserialize($propertyValue, $type, null)); } } return $instance; From 97525b9ec6b21e0d8787f69268a3f49385deeb7f Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 25 Nov 2016 23:14:43 +0800 Subject: [PATCH 106/269] add http://leica-geosystems.com --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index fbb02a3033c..57785d7d1c3 100644 --- a/README.md +++ b/README.md @@ -780,6 +780,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Interactive Intelligence](http://developer.mypurecloud.com/) - [LANDR Audio](https://www.landr.com/) - [Lascaux](http://www.lascaux.it/) +- [Leica Geosystems AG](http://leica-geosystems.com) - [LiveAgent](https://www.ladesk.com/) - [Kabuku](http://www.kabuku.co.jp/en) - [Kuroi](http://kuroiwebdesign.com/) From 8cd881f6a8e9b067586fabc95ad30247095e99b5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 25 Nov 2016 23:26:56 +0800 Subject: [PATCH 107/269] disable appveyor cache (which seems broken) (#4260) --- appveyor.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index ab63a1ed443..b69ac912f94 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -38,5 +38,5 @@ test_script: # generate all petstore clients - .\bin\windows\run-all-petstore.cmd cache: - - C:\maven\ - - C:\Users\appveyor\.m2 +# - C:\maven\ +# - C:\Users\appveyor\.m2 From a61f98afa7c9fd50332cd9e231dd0c18c9f41350 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 28 Nov 2016 10:26:10 +0800 Subject: [PATCH 108/269] add travis test file for objc, swift (#4268) --- .travis.objc_swift_test.yml | 52 +++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 .travis.objc_swift_test.yml diff --git a/.travis.objc_swift_test.yml b/.travis.objc_swift_test.yml new file mode 100644 index 00000000000..a9ffa3fd23e --- /dev/null +++ b/.travis.objc_swift_test.yml @@ -0,0 +1,52 @@ +sudo: required +language: objective-c +osx_image: xcode7.3 + +cache: + directories: + - $HOME/.m2 + - $HOME/.gem + - $HOME/.rvm + - $HOME/.cocoapods + - swagger-api/swagger-codegen/samples/client/petstore/objc/default/SwaggerClientTests/Pods + - swagger-api/swagger-codegen/samples/client/petstore/objc/core-data/SwaggerClientTests/Pods + - swagger-api/swagger-codegen/samples/client/petstore/swift/default/SwaggerClientTests/Pods + - swagger-api/swagger-codegen/samples/client/petstore/swift/promisekit/SwaggerClientTests/Pods + +services: + - docker + +addons: + hosts: + - petstore.swagger.io + +before_install: + - export SW=`pwd` + # show host table to confirm petstore.swagger.io is mapped to localhost + - cat /private/etc/hosts + #- rvm install 2.2.2 > /dev/null 2>&1 + - rvm use 2.2.4 + - gem environment + - gem install cocoapods -v 1.0.1 -N --no-ri --no-rdoc + - gem install xcpretty -N --no-ri --no-rdoc + - pod --version + - pod setup --silent > /dev/null + - brew install xctool + - git clone https://github.com/wing328/swagger-samples + - cd swagger-samples/java/java-jersey-jaxrs && sudo mvn -q jetty:run & + +install: + +script: + # test default objc client + - cd $SW/samples/client/petstore/objc/default/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + # test objc client with coredata + - cd $SW/samples/client/petstore/objc/core-data/SwaggerClientTests && pod install && xctool -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient-Example" -destination platform='iOS Simulator',OS=8.4,name='iPhone 6' test -test-sdk iphonesimulator CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO + - set -o pipefail + # test swift client with promisekit + - cd $SW/samples/client/petstore/swift/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty + # test default swift client + - cd $SW/samples/client/petstore/swift/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty + +env: + - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From e7397d208e58fafdd08bd36bad9b4024e00c38cb Mon Sep 17 00:00:00 2001 From: ChrisJamesC Date: Mon, 28 Nov 2016 16:48:30 +0100 Subject: [PATCH 109/269] Fix linting issues Add missing semicolons and remove trailing space in generated code. --- .../main/resources/TypeScript-Fetch/api.mustache | 8 ++++---- .../typescript-fetch/builds/default/api.ts | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index f1aa9e6c4bd..de492936e72 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -14,7 +14,7 @@ const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -25,7 +25,7 @@ export class BaseAPI { this.basePath = basePath; this.fetch = fetch; } -} +}; {{#models}} {{#model}} @@ -118,7 +118,7 @@ export const {{classname}}FetchParamCreactor = { }; }, {{/operation}} -} +}; /** * {{classname}} - functional programming interface{{#description}} @@ -179,7 +179,7 @@ export const {{classname}}Factory = function (fetch?: FetchAPI, basePath?: strin return {{classname}}Fp.{{nickname}}({{#hasParams}}params{{/hasParams}})(fetch, basePath); }, {{/operation}} - } + }; }; {{/operations}} diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index 0a699f9f75a..99d6195e804 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -23,7 +23,7 @@ const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); export interface FetchArgs { url: string; - options: any; + options: any; } export class BaseAPI { @@ -34,7 +34,7 @@ export class BaseAPI { this.basePath = basePath; this.fetch = fetch; } -} +}; export interface Category { "id"?: number; @@ -293,7 +293,7 @@ export const PetApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * PetApi - functional programming interface @@ -591,7 +591,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }) { return PetApiFp.uploadFile(params)(fetch, basePath); }, - } + }; }; @@ -688,7 +688,7 @@ export const StoreApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * StoreApi - functional programming interface @@ -836,7 +836,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { placeOrder(params: { body?: Order; }) { return StoreApiFp.placeOrder(params)(fetch, basePath); }, - } + }; }; @@ -1032,7 +1032,7 @@ export const UserApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * UserApi - functional programming interface @@ -1318,6 +1318,6 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { updateUser(params: { username: string; body?: User; }) { return UserApiFp.updateUser(params)(fetch, basePath); }, - } + }; }; From 6472baa44e116b39b7844b2370e9439af8ebee50 Mon Sep 17 00:00:00 2001 From: ChrisJamesC Date: Mon, 28 Nov 2016 16:57:10 +0100 Subject: [PATCH 110/269] Fix typos in CONTRIBUTING.md --- CONTRIBUTING.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 32195b7df92..5a169cd7682 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ For a list of variables available in the template, please refer to this [page](h ### Style guide -Code change should conform to the programming style guide of the respective langauages: +Code change should conform to the programming style guide of the respective languages: - Android: https://source.android.com/source/code-style.html - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html @@ -52,8 +52,8 @@ You may find the current code base not 100% conform to the coding style and we w For [Vendor Extensions](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#vendorExtensions), please follow the naming convention below: - For general vendor extension, use lower case and hyphen. e.g. `x-is-unique`, `x-content-type` -- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit` -- For a list of existing vendor extensions in use, please refer to https://github.com/swagger-api/swagger-codegen/wiki/Vendor-Extensions. If you've addaed new vendor extensions as part of your PR, please update the wiki page. +- For language-specified vendor extension, put it in the form of `x-{lang}-{extension-name}`. e.g. `x-objc-operation-id`, `x-java-feign-retry-limit` +- For a list of existing vendor extensions in use, please refer to https://github.com/swagger-api/swagger-codegen/wiki/Vendor-Extensions. If you've added new vendor extensions as part of your PR, please update the wiki page. ### Testing From d2e08835d013e34fb04592843ee6601f939c8bd0 Mon Sep 17 00:00:00 2001 From: ChrisJamesC Date: Tue, 29 Nov 2016 10:12:23 +0100 Subject: [PATCH 111/269] Fix typo in the README --- README.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 57785d7d1c3..b8ef10a2d62 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit ## Compatibility -The OpenAPI Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the OpenAPI Specification: +The OpenAPI Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilities with the OpenAPI Specification: Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- @@ -665,7 +665,7 @@ You can use the [swagger-codegen-maven-plugin](modules/swagger-codegen-maven-plu To push the auto-generated SDK to GitHub, we provide `git_push.sh` to streamline the process. For example: 1) Create a new repository in GitHub (Ref: https://help.github.com/articles/creating-a-new-repository/) - + 2) Generate the SDK ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ @@ -786,7 +786,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Kuroi](http://kuroiwebdesign.com/) - [Kuary](https://kuary.com/) - [Mindera](http://mindera.com/) -- [Mporium](http://mporium.com/) +- [Mporium](http://mporium.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) - [Onedata](http://onedata.org) @@ -800,7 +800,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [QAdept](http://qadept.com/) - [QuantiModo](https://quantimo.do/) - [Rapid7](https://rapid7.com/) -- [Reload! A/S](https://reload.dk/) +- [Reload! A/S](https://reload.dk/) - [REstore](https://www.restore.eu) - [Revault Sàrl](http://revault.ch) - [Riffyn](https://riffyn.com) @@ -810,7 +810,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) -- [TaskData](http://www.taskdata.com/) +- [TaskData](http://www.taskdata.com/) - [ThoughtWorks](https://www.thoughtworks.com) - [uShip](https://www.uship.com/) - [W.UP](http://wup.hu/?siteLang=en) @@ -825,8 +825,8 @@ Here are some companies/projects using Swagger Codegen in production. To add you Swagger Codegen core team members are contributors who have been making significant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. ## API Clients -| Languages | Core Team (join date) | -|:-------------|:-------------| +| Languages | Core Team (join date) | +|:-------------|:-------------| | ActionScript | | | C++ | | | C# | @jimschubert (2016/05/01) | | @@ -836,7 +836,7 @@ Swagger Codegen core team members are contributors who have been making signific | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | | Java | @cbornet (2016/05/01) @xhh (2016/05/01) @epaul (2016/06/04) | | Java (Spring Cloud) | @cbornet (2016/07/19) | -| NodeJS/Javascript | @xhh (2016/05/01) | +| NodeJS/Javascript | @xhh (2016/05/01) | | ObjC | @mateuszmackowiak (2016/05/09) | | Perl | @wing328 (2016/05/01) | | PHP | @arnested (2016/05/01) | @@ -844,13 +844,13 @@ Swagger Codegen core team members are contributors who have been making signific | Ruby | @wing328 (2016/05/01) @zlx (2016/05/22) | | Scala | | | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | -| TypeScript (Node) | @Vrolijkx (2016/05/01) | -| TypeScript (Angular1) | @Vrolijkx (2016/05/01) | +| TypeScript (Node) | @Vrolijkx (2016/05/01) | +| TypeScript (Angular1) | @Vrolijkx (2016/05/01) | | TypeScript (Angular2) | @Vrolijkx (2016/05/01) | | TypeScript (Fetch) | | ## Server Stubs -| Languages | Core Team (date joined) | -|:------------- |:-------------| +| Languages | Core Team (date joined) | +|:------------- |:-------------| | C# ASP.NET5 | @jimschubert (2016/05/01) | | Go Server | @guohuang (2016/06/13) | | Haskell Servant | | @@ -869,7 +869,7 @@ Swagger Codegen core team members are contributors who have been making signific ## Template Creator Here is a list of template creators: * API Clients: - * Akka-Scala: @cchafer + * Akka-Scala: @cchafer * C++ REST: @Danielku15 * C# (.NET 2.0): @who * Clojure: @xhh @@ -878,15 +878,15 @@ Here is a list of template creators: * Go: @wing328 * Java (Retrofit): @0legg * Java (Retrofi2): @emilianobonassi - * Java (Jersey2): @xhh + * Java (Jersey2): @xhh * Java (okhttp-gson): @xhh * Javascript/NodeJS: @jfiala * Javascript (Closure-annotated Angular) @achew22 * Perl: @wing328 * Swift: @tkqubo * Swift 3: @hexelon - * TypeScript (Node): @mhardorf - * TypeScript (Angular1): @mhardorf + * TypeScript (Node): @mhardorf + * TypeScript (Angular1): @mhardorf * TypeScript (Fetch): @leonyu * TypeScript (Angular2): @roni-frantchi * Server Stubs @@ -903,7 +903,7 @@ Here is a list of template creators: * JAX-RS CXF (CDI): @nickcmaynard * PHP Lumen: @abcsum * PHP Slim: @jfastnacht - * Ruby on Rails 5: @zlx + * Ruby on Rails 5: @zlx * Documentation * HTML Doc 2: @jhitchcock * Confluence Wiki: @jhitchcock @@ -912,13 +912,13 @@ Here is a list of template creators: Here are the requirements to become a core team member: - rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors - - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22) + - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22) - regular contributions to the project - about 3 hours per week - for contribution, it can be addressing issues, reviewing PRs submitted by others, submitting PR to fix bugs or make enhancements, etc To join the core team, please reach out to wing328hk@gmail.com (@wing328) for more information. - + To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator. ## License information on Generated Code From 67e0c92720ac617caf89b3b72375a010f57e9696 Mon Sep 17 00:00:00 2001 From: K Pradeep Kumar Reddy Date: Tue, 29 Nov 2016 16:13:29 +0530 Subject: [PATCH 112/269] added my company name to the list of companies. added my company name to the list of companies. My company name is LXL Tech. It is a startup company working on mobile apps --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index b8ef10a2d62..591c7184853 100644 --- a/README.md +++ b/README.md @@ -778,13 +778,14 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Intent HQ](http://www.intenthq.com) - [Interactive Intelligence](http://developer.mypurecloud.com/) +- [Kabuku](http://www.kabuku.co.jp/en) +- [Kuroi](http://kuroiwebdesign.com/) +- [Kuary](https://kuary.com/) - [LANDR Audio](https://www.landr.com/) - [Lascaux](http://www.lascaux.it/) - [Leica Geosystems AG](http://leica-geosystems.com) - [LiveAgent](https://www.ladesk.com/) -- [Kabuku](http://www.kabuku.co.jp/en) -- [Kuroi](http://kuroiwebdesign.com/) -- [Kuary](https://kuary.com/) +- [LXL Tech](http://lxltech.com) - [Mindera](http://mindera.com/) - [Mporium](http://mporium.com/) - [nViso](http://www.nviso.ch/) From b733334eee0769d116a111f062559aedaeb310c9 Mon Sep 17 00:00:00 2001 From: Christopher Chiche Date: Wed, 30 Nov 2016 08:22:38 +0100 Subject: [PATCH 113/269] [Typescript/fetch][Issue4284] Handle query parameters containing colons (#4287) Put query parameters between quotes and access object keys using square brackets to make sure special characters are handled in parameter names. Closes #4284 --- .../resources/TypeScript-Fetch/api.mustache | 16 +- .../typescript-fetch/builds/default/api.ts | 180 ++++++++-------- .../typescript-fetch/builds/es6-target/api.ts | 194 +++++++++--------- .../builds/with-npm-version/api.ts | 194 +++++++++--------- 4 files changed, 292 insertions(+), 292 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 11827d1ddc4..b3cfa638030 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -70,7 +70,7 @@ export const {{classname}}FetchParamCreactor = { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any): FetchArgs { + {{nickname}}({{#hasParams}}params: { {{#allParams}} "{{paramName}}"{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any): FetchArgs { {{#allParams}} {{#required}} // verify required parameter "{{paramName}}" is set @@ -80,11 +80,11 @@ export const {{classname}}FetchParamCreactor = { {{/required}} {{/allParams}} const baseUrl = `{{path}}`{{#pathParams}} - .replace(`{${"{{baseName}}"}}`, `${ params.{{paramName}} }`){{/pathParams}}; + .replace(`{${"{{baseName}}"}}`, `${ params["{{paramName}}"] }`){{/pathParams}}; let urlObj = url.parse(baseUrl, true); {{#hasQueryParams}} urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}} - "{{baseName}}": params.{{paramName}},{{/queryParams}} + "{{baseName}}": params["{{paramName}}"],{{/queryParams}} }); {{/hasQueryParams}} let fetchOptions: RequestInit = {{#supportsES6}}Object.{{/supportsES6}}assign({}, { method: "{{httpMethod}}" }, options); @@ -93,7 +93,7 @@ export const {{classname}}FetchParamCreactor = { {{#hasFormParams}} contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ {{#formParams}} - "{{baseName}}": params.{{paramName}},{{/formParams}} + "{{baseName}}": params["{{paramName}}"],{{/formParams}} }); {{/hasFormParams}} {{#hasBodyParam}} @@ -104,7 +104,7 @@ export const {{classname}}FetchParamCreactor = { {{/hasBodyParam}} {{#hasHeaderParams}} fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}} - "{{baseName}}": params.{{paramName}},{{/headerParams}} + "{{baseName}}": params["{{paramName}}"],{{/headerParams}} }, contentTypeHeader); {{/hasHeaderParams}} {{^hasHeaderParams}} @@ -131,7 +131,7 @@ export const {{classname}}Fp = { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }, {{/hasParams}}options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { + {{nickname}}({{#hasParams}}params: { {{#allParams}}"{{paramName}}"{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }, {{/hasParams}}options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params, {{/hasParams}}options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -157,7 +157,7 @@ export class {{classname}} extends BaseAPI { * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { + {{nickname}}({{#hasParams}}params: { {{#allParams}} "{{paramName}}"{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { return {{classname}}Fp.{{nickname}}({{#hasParams}}params, {{/hasParams}}options)(this.fetch, this.basePath); } {{/operation}} @@ -175,7 +175,7 @@ export const {{classname}}Factory = function (fetch?: FetchAPI, basePath?: strin * {{notes}}{{/notes}}{{#allParams}} * @param {{paramName}} {{description}}{{/allParams}} */ - {{nickname}}({{#hasParams}}params: { {{#allParams}} {{paramName}}{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { + {{nickname}}({{#hasParams}}params: { {{#allParams}} "{{paramName}}"{{^required}}?{{/required}}: {{{dataType}}};{{/allParams}} }, {{/hasParams}}options?: any) { return {{classname}}Fp.{{nickname}}({{#hasParams}}params, {{/hasParams}}options)(fetch, basePath); }, {{/operation}} diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index 52d75f230b7..fdf7cbc5cdc 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -97,7 +97,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): FetchArgs { + addPet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -121,19 +121,19 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = assign({ - "api_key": params.apiKey, + "api_key": params["apiKey"], }, contentTypeHeader); return { url: url.format(urlObj), @@ -145,11 +145,11 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { + findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "status": params.status, + "status": params["status"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -167,11 +167,11 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { + findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "tags": params.tags, + "tags": params["tags"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -189,13 +189,13 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }, options?: any): FetchArgs { + getPetById(params: { "petId": number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -213,7 +213,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): FetchArgs { + updatePet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); @@ -238,21 +238,21 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "name": params.name, - "status": params.status, + "name": params["name"], + "status": params["status"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -269,21 +269,21 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } const baseUrl = `/pet/{petId}/uploadImage` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "additionalMetadata": params.additionalMetadata, - "file": params.file, + "additionalMetadata": params["additionalMetadata"], + "file": params["file"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -304,7 +304,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -322,7 +322,7 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -339,7 +339,7 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -356,7 +356,7 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -373,7 +373,7 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -390,7 +390,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -409,7 +409,7 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -428,7 +428,7 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -451,7 +451,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** @@ -460,7 +460,7 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** @@ -468,7 +468,7 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** @@ -476,7 +476,7 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** @@ -484,7 +484,7 @@ export class PetApi extends BaseAPI { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** @@ -492,7 +492,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** @@ -502,7 +502,7 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** @@ -512,7 +512,7 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -527,7 +527,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(fetch, basePath); }, /** @@ -536,7 +536,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** @@ -544,7 +544,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** @@ -552,7 +552,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** @@ -560,7 +560,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** @@ -568,7 +568,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** @@ -578,7 +578,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** @@ -588,7 +588,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(fetch, basePath); }, }; @@ -604,13 +604,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { + deleteOrder(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); @@ -646,13 +646,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): FetchArgs { + getOrderById(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -670,7 +670,7 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): FetchArgs { + placeOrder(params: { "body"?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -699,7 +699,7 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -732,7 +732,7 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -749,7 +749,7 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -772,7 +772,7 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** @@ -787,7 +787,7 @@ export class StoreApi extends BaseAPI { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** @@ -795,7 +795,7 @@ export class StoreApi extends BaseAPI { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -810,7 +810,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** @@ -825,7 +825,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** @@ -833,7 +833,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, }; @@ -849,7 +849,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): FetchArgs { + createUser(params: { "body"?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -872,7 +872,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -895,7 +895,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -918,13 +918,13 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): FetchArgs { + deleteUser(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); @@ -942,13 +942,13 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): FetchArgs { + getUserByName(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -967,12 +967,12 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "username": params.username, - "password": params.password, + "username": params["username"], + "password": params["password"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -1009,13 +1009,13 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { + updateUser(params: { "username": string; "body"?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); @@ -1043,7 +1043,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1060,7 +1060,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1077,7 +1077,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1094,7 +1094,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1111,7 +1111,7 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1129,7 +1129,7 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1163,7 +1163,7 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1186,7 +1186,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** @@ -1194,7 +1194,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** @@ -1202,7 +1202,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** @@ -1210,7 +1210,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** @@ -1218,7 +1218,7 @@ export class UserApi extends BaseAPI { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** @@ -1227,7 +1227,7 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** @@ -1243,7 +1243,7 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1258,7 +1258,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(fetch, basePath); }, /** @@ -1266,7 +1266,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** @@ -1274,7 +1274,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** @@ -1282,7 +1282,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** @@ -1290,7 +1290,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** @@ -1299,7 +1299,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** @@ -1315,7 +1315,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(fetch, basePath); }, }; diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index fdfa555e86d..2a5a95b3c21 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -33,7 +33,7 @@ export class BaseAPI { this.basePath = basePath; this.fetch = fetch; } -} +}; export interface Category { "id"?: number; @@ -96,7 +96,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): FetchArgs { + addPet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); @@ -120,19 +120,19 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = Object.assign({ - "api_key": params.apiKey, + "api_key": params["apiKey"], }, contentTypeHeader); return { url: url.format(urlObj), @@ -144,11 +144,11 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { + findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { - "status": params.status, + "status": params["status"], }); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -166,11 +166,11 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { + findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { - "tags": params.tags, + "tags": params["tags"], }); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -188,13 +188,13 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }, options?: any): FetchArgs { + getPetById(params: { "petId": number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -212,7 +212,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): FetchArgs { + updatePet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "PUT" }, options); @@ -237,21 +237,21 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "name": params.name, - "status": params.status, + "name": params["name"], + "status": params["status"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -268,21 +268,21 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } const baseUrl = `/pet/{petId}/uploadImage` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "additionalMetadata": params.additionalMetadata, - "file": params.file, + "additionalMetadata": params["additionalMetadata"], + "file": params["file"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -292,7 +292,7 @@ export const PetApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * PetApi - functional programming interface @@ -303,7 +303,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -321,7 +321,7 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -338,7 +338,7 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -355,7 +355,7 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -372,7 +372,7 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -389,7 +389,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -408,7 +408,7 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -427,7 +427,7 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -450,7 +450,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** @@ -459,7 +459,7 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** @@ -467,7 +467,7 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** @@ -475,7 +475,7 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** @@ -483,7 +483,7 @@ export class PetApi extends BaseAPI { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** @@ -491,7 +491,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** @@ -501,7 +501,7 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** @@ -511,7 +511,7 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -526,7 +526,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(fetch, basePath); }, /** @@ -535,7 +535,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** @@ -543,7 +543,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** @@ -551,7 +551,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** @@ -559,7 +559,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** @@ -567,7 +567,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** @@ -577,7 +577,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** @@ -587,10 +587,10 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(fetch, basePath); }, - } + }; }; @@ -603,13 +603,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { + deleteOrder(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); @@ -645,13 +645,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): FetchArgs { + getOrderById(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -669,7 +669,7 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): FetchArgs { + placeOrder(params: { "body"?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); @@ -687,7 +687,7 @@ export const StoreApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * StoreApi - functional programming interface @@ -698,7 +698,7 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -731,7 +731,7 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -748,7 +748,7 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -771,7 +771,7 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** @@ -786,7 +786,7 @@ export class StoreApi extends BaseAPI { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** @@ -794,7 +794,7 @@ export class StoreApi extends BaseAPI { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -809,7 +809,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** @@ -824,7 +824,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** @@ -832,10 +832,10 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, - } + }; }; @@ -848,7 +848,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): FetchArgs { + createUser(params: { "body"?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); @@ -871,7 +871,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); @@ -894,7 +894,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "POST" }, options); @@ -917,13 +917,13 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): FetchArgs { + deleteUser(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); @@ -941,13 +941,13 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): FetchArgs { + getUserByName(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -966,12 +966,12 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = Object.assign({}, urlObj.query, { - "username": params.username, - "password": params.password, + "username": params["username"], + "password": params["password"], }); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -1008,13 +1008,13 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { + updateUser(params: { "username": string; "body"?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = Object.assign({}, { method: "PUT" }, options); @@ -1031,7 +1031,7 @@ export const UserApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * UserApi - functional programming interface @@ -1042,7 +1042,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1059,7 +1059,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1076,7 +1076,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1093,7 +1093,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1110,7 +1110,7 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1128,7 +1128,7 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1162,7 +1162,7 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1185,7 +1185,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** @@ -1193,7 +1193,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** @@ -1201,7 +1201,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** @@ -1209,7 +1209,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** @@ -1217,7 +1217,7 @@ export class UserApi extends BaseAPI { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** @@ -1226,7 +1226,7 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** @@ -1242,7 +1242,7 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1257,7 +1257,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(fetch, basePath); }, /** @@ -1265,7 +1265,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** @@ -1273,7 +1273,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** @@ -1281,7 +1281,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** @@ -1289,7 +1289,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** @@ -1298,7 +1298,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** @@ -1314,9 +1314,9 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(fetch, basePath); }, - } + }; }; diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index 611766ecd6b..fdf7cbc5cdc 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -34,7 +34,7 @@ export class BaseAPI { this.basePath = basePath; this.fetch = fetch; } -} +}; export interface Category { "id"?: number; @@ -97,7 +97,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): FetchArgs { + addPet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -121,19 +121,19 @@ export const PetApiFetchParamCreactor = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): FetchArgs { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling deletePet"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; fetchOptions.headers = assign({ - "api_key": params.apiKey, + "api_key": params["apiKey"], }, contentTypeHeader); return { url: url.format(urlObj), @@ -145,11 +145,11 @@ export const PetApiFetchParamCreactor = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): FetchArgs { + findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "status": params.status, + "status": params["status"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -167,11 +167,11 @@ export const PetApiFetchParamCreactor = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): FetchArgs { + findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "tags": params.tags, + "tags": params["tags"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -189,13 +189,13 @@ export const PetApiFetchParamCreactor = { * 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 */ - getPetById(params: { petId: number; }, options?: any): FetchArgs { + getPetById(params: { "petId": number; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling getPetById"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -213,7 +213,7 @@ export const PetApiFetchParamCreactor = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): FetchArgs { + updatePet(params: { "body"?: Pet; }, options?: any): FetchArgs { const baseUrl = `/pet`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); @@ -238,21 +238,21 @@ export const PetApiFetchParamCreactor = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): FetchArgs { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling updatePetWithForm"); } const baseUrl = `/pet/{petId}` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "name": params.name, - "status": params.status, + "name": params["name"], + "status": params["status"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -269,21 +269,21 @@ export const PetApiFetchParamCreactor = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): FetchArgs { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): FetchArgs { // verify required parameter "petId" is set if (params["petId"] == null) { throw new Error("Missing required parameter petId when calling uploadFile"); } const baseUrl = `/pet/{petId}/uploadImage` - .replace(`{${"petId"}}`, `${ params.petId }`); + .replace(`{${"petId"}}`, `${ params["petId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "additionalMetadata": params.additionalMetadata, - "file": params.file, + "additionalMetadata": params["additionalMetadata"], + "file": params["file"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -293,7 +293,7 @@ export const PetApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * PetApi - functional programming interface @@ -304,7 +304,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -322,7 +322,7 @@ export const PetApiFp = { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -339,7 +339,7 @@ export const PetApiFp = { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -356,7 +356,7 @@ export const PetApiFp = { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { + findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -373,7 +373,7 @@ export const PetApiFp = { * 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 */ - getPetById(params: { petId: number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -390,7 +390,7 @@ export const PetApiFp = { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -409,7 +409,7 @@ export const PetApiFp = { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -428,7 +428,7 @@ export const PetApiFp = { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -451,7 +451,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(this.fetch, this.basePath); } /** @@ -460,7 +460,7 @@ export class PetApi extends BaseAPI { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(this.fetch, this.basePath); } /** @@ -468,7 +468,7 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(this.fetch, this.basePath); } /** @@ -476,7 +476,7 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(this.fetch, this.basePath); } /** @@ -484,7 +484,7 @@ export class PetApi extends BaseAPI { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(this.fetch, this.basePath); } /** @@ -492,7 +492,7 @@ export class PetApi extends BaseAPI { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(this.fetch, this.basePath); } /** @@ -502,7 +502,7 @@ export class PetApi extends BaseAPI { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(this.fetch, this.basePath); } /** @@ -512,7 +512,7 @@ export class PetApi extends BaseAPI { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(this.fetch, this.basePath); } }; @@ -527,7 +527,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - addPet(params: { body?: Pet; }, options?: any) { + addPet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.addPet(params, options)(fetch, basePath); }, /** @@ -536,7 +536,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param petId Pet id to delete * @param apiKey */ - deletePet(params: { petId: number; apiKey?: string; }, options?: any) { + deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any) { return PetApiFp.deletePet(params, options)(fetch, basePath); }, /** @@ -544,7 +544,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter */ - findPetsByStatus(params: { status?: Array; }, options?: any) { + findPetsByStatus(params: { "status"?: Array; }, options?: any) { return PetApiFp.findPetsByStatus(params, options)(fetch, basePath); }, /** @@ -552,7 +552,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by */ - findPetsByTags(params: { tags?: Array; }, options?: any) { + findPetsByTags(params: { "tags"?: Array; }, options?: any) { return PetApiFp.findPetsByTags(params, options)(fetch, basePath); }, /** @@ -560,7 +560,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getPetById(params: { petId: number; }, options?: any) { + getPetById(params: { "petId": number; }, options?: any) { return PetApiFp.getPetById(params, options)(fetch, basePath); }, /** @@ -568,7 +568,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body Pet object that needs to be added to the store */ - updatePet(params: { body?: Pet; }, options?: any) { + updatePet(params: { "body"?: Pet; }, options?: any) { return PetApiFp.updatePet(params, options)(fetch, basePath); }, /** @@ -578,7 +578,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param name Updated name of the pet * @param status Updated status of the pet */ - updatePetWithForm(params: { petId: string; name?: string; status?: string; }, options?: any) { + updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any) { return PetApiFp.updatePetWithForm(params, options)(fetch, basePath); }, /** @@ -588,10 +588,10 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param additionalMetadata Additional data to pass to server * @param file file to upload */ - uploadFile(params: { petId: number; additionalMetadata?: string; file?: any; }, options?: any) { + uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any) { return PetApiFp.uploadFile(params, options)(fetch, basePath); }, - } + }; }; @@ -604,13 +604,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): FetchArgs { + deleteOrder(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling deleteOrder"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); @@ -646,13 +646,13 @@ export const StoreApiFetchParamCreactor = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): FetchArgs { + getOrderById(params: { "orderId": string; }, options?: any): FetchArgs { // verify required parameter "orderId" is set if (params["orderId"] == null) { throw new Error("Missing required parameter orderId when calling getOrderById"); } const baseUrl = `/store/order/{orderId}` - .replace(`{${"orderId"}}`, `${ params.orderId }`); + .replace(`{${"orderId"}}`, `${ params["orderId"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -670,7 +670,7 @@ export const StoreApiFetchParamCreactor = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): FetchArgs { + placeOrder(params: { "body"?: Order; }, options?: any): FetchArgs { const baseUrl = `/store/order`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -688,7 +688,7 @@ export const StoreApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * StoreApi - functional programming interface @@ -699,7 +699,7 @@ export const StoreApiFp = { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -732,7 +732,7 @@ export const StoreApiFp = { * 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 */ - getOrderById(params: { orderId: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -749,7 +749,7 @@ export const StoreApiFp = { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -772,7 +772,7 @@ export class StoreApi extends BaseAPI { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(this.fetch, this.basePath); } /** @@ -787,7 +787,7 @@ export class StoreApi extends BaseAPI { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(this.fetch, this.basePath); } /** @@ -795,7 +795,7 @@ export class StoreApi extends BaseAPI { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(this.fetch, this.basePath); } }; @@ -810,7 +810,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - deleteOrder(params: { orderId: string; }, options?: any) { + deleteOrder(params: { "orderId": string; }, options?: any) { return StoreApiFp.deleteOrder(params, options)(fetch, basePath); }, /** @@ -825,7 +825,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * 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 */ - getOrderById(params: { orderId: string; }, options?: any) { + getOrderById(params: { "orderId": string; }, options?: any) { return StoreApiFp.getOrderById(params, options)(fetch, basePath); }, /** @@ -833,10 +833,10 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body order placed for purchasing the pet */ - placeOrder(params: { body?: Order; }, options?: any) { + placeOrder(params: { "body"?: Order; }, options?: any) { return StoreApiFp.placeOrder(params, options)(fetch, basePath); }, - } + }; }; @@ -849,7 +849,7 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): FetchArgs { + createUser(params: { "body"?: User; }, options?: any): FetchArgs { const baseUrl = `/user`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -872,7 +872,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithArray`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -895,7 +895,7 @@ export const UserApiFetchParamCreactor = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): FetchArgs { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): FetchArgs { const baseUrl = `/user/createWithList`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "POST" }, options); @@ -918,13 +918,13 @@ export const UserApiFetchParamCreactor = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): FetchArgs { + deleteUser(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling deleteUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); @@ -942,13 +942,13 @@ export const UserApiFetchParamCreactor = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): FetchArgs { + getUserByName(params: { "username": string; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling getUserByName"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -967,12 +967,12 @@ export const UserApiFetchParamCreactor = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): FetchArgs { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); urlObj.query = assign({}, urlObj.query, { - "username": params.username, - "password": params.password, + "username": params["username"], + "password": params["password"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -1009,13 +1009,13 @@ export const UserApiFetchParamCreactor = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): FetchArgs { + updateUser(params: { "username": string; "body"?: User; }, options?: any): FetchArgs { // verify required parameter "username" is set if (params["username"] == null) { throw new Error("Missing required parameter username when calling updateUser"); } const baseUrl = `/user/{username}` - .replace(`{${"username"}}`, `${ params.username }`); + .replace(`{${"username"}}`, `${ params["username"] }`); let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); @@ -1032,7 +1032,7 @@ export const UserApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * UserApi - functional programming interface @@ -1043,7 +1043,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1060,7 +1060,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1077,7 +1077,7 @@ export const UserApiFp = { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1094,7 +1094,7 @@ export const UserApiFp = { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1111,7 +1111,7 @@ export const UserApiFp = { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1129,7 +1129,7 @@ export const UserApiFp = { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1163,7 +1163,7 @@ export const UserApiFp = { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -1186,7 +1186,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(this.fetch, this.basePath); } /** @@ -1194,7 +1194,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(this.fetch, this.basePath); } /** @@ -1202,7 +1202,7 @@ export class UserApi extends BaseAPI { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(this.fetch, this.basePath); } /** @@ -1210,7 +1210,7 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(this.fetch, this.basePath); } /** @@ -1218,7 +1218,7 @@ export class UserApi extends BaseAPI { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(this.fetch, this.basePath); } /** @@ -1227,7 +1227,7 @@ export class UserApi extends BaseAPI { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(this.fetch, this.basePath); } /** @@ -1243,7 +1243,7 @@ export class UserApi extends BaseAPI { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(this.fetch, this.basePath); } }; @@ -1258,7 +1258,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param body Created user object */ - createUser(params: { body?: User; }, options?: any) { + createUser(params: { "body"?: User; }, options?: any) { return UserApiFp.createUser(params, options)(fetch, basePath); }, /** @@ -1266,7 +1266,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithArrayInput(params: { body?: Array; }, options?: any) { + createUsersWithArrayInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithArrayInput(params, options)(fetch, basePath); }, /** @@ -1274,7 +1274,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param body List of user object */ - createUsersWithListInput(params: { body?: Array; }, options?: any) { + createUsersWithListInput(params: { "body"?: Array; }, options?: any) { return UserApiFp.createUsersWithListInput(params, options)(fetch, basePath); }, /** @@ -1282,7 +1282,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * This can only be done by the logged in user. * @param username The name that needs to be deleted */ - deleteUser(params: { username: string; }, options?: any) { + deleteUser(params: { "username": string; }, options?: any) { return UserApiFp.deleteUser(params, options)(fetch, basePath); }, /** @@ -1290,7 +1290,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * * @param username The name that needs to be fetched. Use user1 for testing. */ - getUserByName(params: { username: string; }, options?: any) { + getUserByName(params: { "username": string; }, options?: any) { return UserApiFp.getUserByName(params, options)(fetch, basePath); }, /** @@ -1299,7 +1299,7 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username The user name for login * @param password The password for login in clear text */ - loginUser(params: { username?: string; password?: string; }, options?: any) { + loginUser(params: { "username"?: string; "password"?: string; }, options?: any) { return UserApiFp.loginUser(params, options)(fetch, basePath); }, /** @@ -1315,9 +1315,9 @@ export const UserApiFactory = function (fetch?: FetchAPI, basePath?: string) { * @param username name that need to be deleted * @param body Updated user object */ - updateUser(params: { username: string; body?: User; }, options?: any) { + updateUser(params: { "username": string; "body"?: User; }, options?: any) { return UserApiFp.updateUser(params, options)(fetch, basePath); }, - } + }; }; From a603ccb59505962e63236bf4e497ef1f2ef8a8af Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Nov 2016 17:41:55 +0800 Subject: [PATCH 114/269] [Dart] add auto-generated documentation (#4291) * new files for dart client * update doc for dart * update api and model doc for dart * update dart petstore sample * update dart doc * update dart petstore sample * update dart petstore sample * update dart client installation instruction --- bin/dart-petstore.sh | 2 +- .../codegen/languages/DartClientCodegen.java | 19 + .../src/main/resources/dart/README.mustache | 133 ++++++ .../src/main/resources/dart/api_doc.mustache | 87 ++++ .../main/resources/dart/object_doc.mustache | 16 + .../client/petstore/dart/swagger/README.md | 122 ++++++ .../petstore/dart/swagger/docs/ApiResponse.md | 17 + .../petstore/dart/swagger/docs/Category.md | 16 + .../petstore/dart/swagger/docs/Order.md | 20 + .../client/petstore/dart/swagger/docs/Pet.md | 20 + .../petstore/dart/swagger/docs/PetApi.md | 397 ++++++++++++++++++ .../petstore/dart/swagger/docs/StoreApi.md | 192 +++++++++ .../client/petstore/dart/swagger/docs/Tag.md | 16 + .../client/petstore/dart/swagger/docs/User.md | 22 + .../petstore/dart/swagger/docs/UserApi.md | 367 ++++++++++++++++ 15 files changed, 1445 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-codegen/src/main/resources/dart/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/api_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/object_doc.mustache create mode 100644 samples/client/petstore/dart/swagger/README.md create mode 100644 samples/client/petstore/dart/swagger/docs/ApiResponse.md create mode 100644 samples/client/petstore/dart/swagger/docs/Category.md create mode 100644 samples/client/petstore/dart/swagger/docs/Order.md create mode 100644 samples/client/petstore/dart/swagger/docs/Pet.md create mode 100644 samples/client/petstore/dart/swagger/docs/PetApi.md create mode 100644 samples/client/petstore/dart/swagger/docs/StoreApi.md create mode 100644 samples/client/petstore/dart/swagger/docs/Tag.md create mode 100644 samples/client/petstore/dart/swagger/docs/User.md create mode 100644 samples/client/petstore/dart/swagger/docs/UserApi.md diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh index 357cbac45ff..bfb9e8179f0 100755 --- a/bin/dart-petstore.sh +++ b/bin/dart-petstore.sh @@ -27,7 +27,7 @@ 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.yaml -l dart -o samples/client/petstore/dart/swagger" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/dart -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger" # then options to generate the library for vm would be: #ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l dart -o samples/client/petstore/dart/swagger_vm -DbrowserClient=false -DpubName=swagger_vm" diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 1d90984f8b0..8d2591f0521 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -25,6 +25,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { protected String pubVersion = "1.0.0"; protected String pubDescription = "Swagger API client"; protected String sourceFolder = ""; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public DartClientCodegen() { super(); @@ -39,6 +41,8 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { embeddedTemplateDir = templateDir = "dart"; apiPackage = "lib.api"; modelPackage = "lib.model"; + modelDocTemplateFiles.put("object_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); setReservedWordsLowerCase( Arrays.asList( @@ -145,6 +149,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + final String libFolder = sourceFolder + File.separator + "lib"; supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); supportingFiles.add(new SupportingFile("analysis_options.mustache", "", ".analysis_options")); @@ -160,6 +168,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @@ -179,6 +188,16 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at diff --git a/modules/swagger-codegen/src/main/resources/dart/README.mustache b/modules/swagger-codegen/src/main/resources/dart/README.mustache new file mode 100644 index 00000000000..c6620349a4a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/README.mustache @@ -0,0 +1,133 @@ +# {{pubName}} +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This Dart package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +{{#artifactVersion}} +- Package version: {{artifactVersion}} +{{/artifactVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Requirements + +Dart 1.20.0 and later + +## Installation & Usage + +### Github +If this Dart package is published to Github, please include the following in pubspec.yaml +``` +name: {{pubName}} +version: {{pubVersion}} +description: {{pubDescription}} +dependencies: + {{pubName}}: + git: https://github.com/{{gitUserId}}/{{gitRepoId}}.git + version: 'any' +``` + +### Local +To use the package in your local drive, please include the following in pubspec.yaml +``` +dependencies: + {{pubName}}: + path: /path/to/{{pubName}} +``` + +## Tests + +TODO + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```dart +import 'package:{{pubName}}/api.dart'; +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +{{#hasAuthMethods}} +{{#authMethods}} +{{#isBasic}} +// TODO Configure HTTP basic authorization: {{{name}}} +//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME'; +//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD'; +{{/isBasic}} +{{#isApiKey}} +// TODO Configure API key authorization: {{{name}}} +//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +// uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer"; +{{/isApiKey}} +{{#isOAuth}} +// TODO Configure OAuth2 access token for authorization: {{{name}}} +//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} + +var api_instance = new {{classname}}(); +{{#allParams}} +var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}new {{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +{{/allParams}} + +try { + {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}} + print(result); + {{/returnType}} +} catch (e) { + print("Exception when calling {{classname}}->{{operationId}}: $e\n"); +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}/{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}/{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization + +{{^authMethods}} All endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}}## {{{name}}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{{keyParamName}}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache b/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache new file mode 100644 index 00000000000..06491380ae8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache @@ -0,0 +1,87 @@ +# {{pubName}}.api.{{classname}}{{#description}} +{{description}}{{/description}} + +## Load the API package +```dart +import 'package:{{pubName}}/api.dart'; +``` + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```dart +import '{{pubName}}.api'; +import '{{pubName}}.model'; +{{#hasAuthMethods}} +{{#authMethods}} +{{#isBasic}} +// TODO Configure HTTP basic authorization: {{{name}}} +//{{pubName}}.api.Configuration.username = 'YOUR_USERNAME'; +//{{pubName}}.api.Configuration.password = 'YOUR_PASSWORD'; +{{/isBasic}} +{{#isApiKey}} +// TODO Configure API key authorization: {{{name}}} +//{{pubName}}.api.Configuration.apiKey{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +// uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//{{pubName}}.api.Configuration.apiKeyPrefix{'{{{keyParamName}}}'} = "Bearer"; +{{/isApiKey}} +{{#isOAuth}} +// TODO Configure OAuth2 access token for authorization: {{{name}}} +//{{pubName}}.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; +{{/isOAuth}} +{{/authMethods}} +{{/hasAuthMethods}} + +var api_instance = new {{classname}}(); +{{#allParams}} +var {{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}new {{dataType}}(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; // {{{dataType}}} | {{{description}}} +{{/allParams}} + +try { + {{#returnType}}var result = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}} + print(result); + {{/returnType}} +} catch (e) { + print("Exception when calling {{classname}}->{{operationId}}: $e\n"); +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/dart/object_doc.mustache b/modules/swagger-codegen/src/main/resources/dart/object_doc.mustache new file mode 100644 index 00000000000..9ad4463997b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/object_doc.mustache @@ -0,0 +1,16 @@ +{{#models}}{{#model}}# {{pubName}}.model.{{classname}} + +## Load the model package +```dart +import 'package:{{pubName}}/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/samples/client/petstore/dart/swagger/README.md b/samples/client/petstore/dart/swagger/README.md new file mode 100644 index 00000000000..4eb573e3d32 --- /dev/null +++ b/samples/client/petstore/dart/swagger/README.md @@ -0,0 +1,122 @@ +# swagger +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + +This Dart package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- Build date: 2016-11-30T17:17:22.024+08:00 +- Build package: class io.swagger.codegen.languages.DartClientCodegen + +## Requirements + +Dart 1.20.0 and later + +## Installation & Usage + +### Github +If this Dart package is published to Github, please include the following in pubspec.yaml +``` +name: swagger +version: 1.0.0 +description: Swagger API client +dependencies: + swagger: + git: https://github.com/GIT_USER_ID/GIT_REPO_ID.git + version: 'any' +``` + +### Local +To use the package in your local drive, please include the following in pubspec.yaml +``` +dependencies: + swagger: + path: /path/to/swagger +``` + +## Tests + +TODO + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```dart +import 'package:swagger/api.dart'; + +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var body = new Pet(); // Pet | Pet object that needs to be added to the store + +try { + api_instance.addPet(body); +} catch (e) { + print("Exception when calling PetApi->addPet: $e\n"); +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs//PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs//PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs//PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs//PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs//PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs//PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs//PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs//PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs//StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs//StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs//StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs//StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs//UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs//UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs//UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs//UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs//UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs//UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs//UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs//UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [ApiResponse](docs//ApiResponse.md) + - [Category](docs//Category.md) + - [Order](docs//Order.md) + - [Pet](docs//Pet.md) + - [Tag](docs//Tag.md) + - [User](docs//User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/dart/swagger/docs/ApiResponse.md b/samples/client/petstore/dart/swagger/docs/ApiResponse.md new file mode 100644 index 00000000000..7bc0c834d78 --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/ApiResponse.md @@ -0,0 +1,17 @@ +# swagger.model.ApiResponse + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **int** | | [optional] [default to null] +**type** | **String** | | [optional] [default to null] +**message** | **String** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/Category.md b/samples/client/petstore/dart/swagger/docs/Category.md new file mode 100644 index 00000000000..3f5d01c5e1c --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/Category.md @@ -0,0 +1,16 @@ +# swagger.model.Category + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] [default to null] +**name** | **String** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/Order.md b/samples/client/petstore/dart/swagger/docs/Order.md new file mode 100644 index 00000000000..c076322a76e --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/Order.md @@ -0,0 +1,20 @@ +# swagger.model.Order + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] [default to null] +**petId** | **int** | | [optional] [default to null] +**quantity** | **int** | | [optional] [default to null] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] [default to null] +**status** | **String** | Order Status | [optional] [default to null] +**complete** | **bool** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/Pet.md b/samples/client/petstore/dart/swagger/docs/Pet.md new file mode 100644 index 00000000000..3f8629fbd43 --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/Pet.md @@ -0,0 +1,20 @@ +# swagger.model.Pet + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] [default to null] +**category** | [**Category**](Category.md) | | [optional] [default to null] +**name** | **String** | | [default to null] +**photoUrls** | **List<String>** | | [default to []] +**tags** | [**List<Tag>**](Tag.md) | | [optional] [default to []] +**status** | **String** | pet status in the store | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/PetApi.md b/samples/client/petstore/dart/swagger/docs/PetApi.md new file mode 100644 index 00000000000..310ea9ee57b --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/PetApi.md @@ -0,0 +1,397 @@ +# swagger.api.PetApi + +## Load the API package +```dart +import 'package:swagger/api.dart'; +``` + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var body = new Pet(); // Pet | Pet object that needs to be added to the store + +try { + api_instance.addPet(body); +} catch (e) { + print("Exception when calling PetApi->addPet: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var petId = 789; // int | Pet id to delete +var apiKey = apiKey_example; // String | + +try { + api_instance.deletePet(petId, apiKey); +} catch (e) { + print("Exception when calling PetApi->deletePet: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **int**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByStatus** +> List findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var status = []; // List | Status values that need to be considered for filter + +try { + var result = api_instance.findPetsByStatus(status); + print(result); +} catch (e) { + print("Exception when calling PetApi->findPetsByStatus: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **findPetsByTags** +> List findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var tags = []; // List | Tags to filter by + +try { + var result = api_instance.findPetsByTags(tags); + print(result); +} catch (e) { + print("Exception when calling PetApi->findPetsByTags: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure API key authorization: api_key +//swagger.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +// uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//swagger.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; + +var api_instance = new PetApi(); +var petId = 789; // int | ID of pet to return + +try { + var result = api_instance.getPetById(petId); + print(result); +} catch (e) { + print("Exception when calling PetApi->getPetById: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **int**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var body = new Pet(); // Pet | Pet object that needs to be added to the store + +try { + api_instance.updatePet(body); +} catch (e) { + print("Exception when calling PetApi->updatePet: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var petId = 789; // int | ID of pet that needs to be updated +var name = name_example; // String | Updated name of the pet +var status = status_example; // String | Updated status of the pet + +try { + api_instance.updatePetWithForm(petId, name, status); +} catch (e) { + print("Exception when calling PetApi->updatePetWithForm: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **int**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **uploadFile** +> ApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure OAuth2 access token for authorization: petstore_auth +//swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; + +var api_instance = new PetApi(); +var petId = 789; // int | ID of pet to update +var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server +var file = /path/to/file.txt; // MultipartFile | file to upload + +try { + var result = api_instance.uploadFile(petId, additionalMetadata, file); + print(result); +} catch (e) { + print("Exception when calling PetApi->uploadFile: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **int**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **MultipartFile**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/dart/swagger/docs/StoreApi.md b/samples/client/petstore/dart/swagger/docs/StoreApi.md new file mode 100644 index 00000000000..a51bfe07cfc --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/StoreApi.md @@ -0,0 +1,192 @@ +# swagger.api.StoreApi + +## Load the API package +```dart +import 'package:swagger/api.dart'; +``` + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new StoreApi(); +var orderId = orderId_example; // String | ID of the order that needs to be deleted + +try { + api_instance.deleteOrder(orderId); +} catch (e) { + print("Exception when calling StoreApi->deleteOrder: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getInventory** +> Map getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; +// TODO Configure API key authorization: api_key +//swagger.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; +// uncomment below to setup prefix (e.g. Bearer) for API key, if needed +//swagger.api.Configuration.apiKeyPrefix{'api_key'} = "Bearer"; + +var api_instance = new StoreApi(); + +try { + var result = api_instance.getInventory(); + print(result); +} catch (e) { + print("Exception when calling StoreApi->getInventory: $e\n"); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new StoreApi(); +var orderId = 789; // int | ID of pet that needs to be fetched + +try { + var result = api_instance.getOrderById(orderId); + print(result); +} catch (e) { + print("Exception when calling StoreApi->getOrderById: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **int**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new StoreApi(); +var body = new Order(); // Order | order placed for purchasing the pet + +try { + var result = api_instance.placeOrder(body); + print(result); +} catch (e) { + print("Exception when calling StoreApi->placeOrder: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/dart/swagger/docs/Tag.md b/samples/client/petstore/dart/swagger/docs/Tag.md new file mode 100644 index 00000000000..c644f1e826a --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/Tag.md @@ -0,0 +1,16 @@ +# swagger.model.Tag + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] [default to null] +**name** | **String** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/User.md b/samples/client/petstore/dart/swagger/docs/User.md new file mode 100644 index 00000000000..d49bb37d96c --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/User.md @@ -0,0 +1,22 @@ +# swagger.model.User + +## Load the model package +```dart +import 'package:swagger/api.dart'; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **int** | | [optional] [default to null] +**username** | **String** | | [optional] [default to null] +**firstName** | **String** | | [optional] [default to null] +**lastName** | **String** | | [optional] [default to null] +**email** | **String** | | [optional] [default to null] +**password** | **String** | | [optional] [default to null] +**phone** | **String** | | [optional] [default to null] +**userStatus** | **int** | User Status | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/dart/swagger/docs/UserApi.md b/samples/client/petstore/dart/swagger/docs/UserApi.md new file mode 100644 index 00000000000..bc26daaa1d1 --- /dev/null +++ b/samples/client/petstore/dart/swagger/docs/UserApi.md @@ -0,0 +1,367 @@ +# swagger.api.UserApi + +## Load the API package +```dart +import 'package:swagger/api.dart'; +``` + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var body = new User(); // User | Created user object + +try { + api_instance.createUser(body); +} catch (e) { + print("Exception when calling UserApi->createUser: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var body = [new List<User>()]; // List | List of user object + +try { + api_instance.createUsersWithArrayInput(body); +} catch (e) { + print("Exception when calling UserApi->createUsersWithArrayInput: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var body = [new List<User>()]; // List | List of user object + +try { + api_instance.createUsersWithListInput(body); +} catch (e) { + print("Exception when calling UserApi->createUsersWithListInput: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var username = username_example; // String | The name that needs to be deleted + +try { + api_instance.deleteUser(username); +} catch (e) { + print("Exception when calling UserApi->deleteUser: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var username = username_example; // String | The name that needs to be fetched. Use user1 for testing. + +try { + var result = api_instance.getUserByName(username); + print(result); +} catch (e) { + print("Exception when calling UserApi->getUserByName: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var username = username_example; // String | The user name for login +var password = password_example; // String | The password for login in clear text + +try { + var result = api_instance.loginUser(username, password); + print(result); +} catch (e) { + print("Exception when calling UserApi->loginUser: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); + +try { + api_instance.logoutUser(); +} catch (e) { + print("Exception when calling UserApi->logoutUser: $e\n"); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```dart +import 'swagger.api'; +import 'swagger.model'; + +var api_instance = new UserApi(); +var username = username_example; // String | name that need to be deleted +var body = new User(); // User | Updated user object + +try { + api_instance.updateUser(username, body); +} catch (e) { + print("Exception when calling UserApi->updateUser: $e\n"); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + From 165811134571ecb4e6e7bd4352dd1f37d9a7b1fd Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Nov 2016 17:43:58 +0800 Subject: [PATCH 115/269] add swagger codegen evangelist program --- README.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 591c7184853..646323bc220 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) - [Swagger Codegen Core Team](#swagger-codegen-core-team) + - [Swagger Codegen Evangelist](#swagger-codegen-evangelist) - [License](#license) @@ -922,7 +923,21 @@ Here are the requirements to become a core team member: To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator. -## License information on Generated Code +# Swagger Codegen Evangelist + +Swagger Codegen Evangelist shoulders one or more of the following responsibilities: + +- publishes articles on the benefit of Swagger Codegen +- organizes local Meetups +- presents the benefits of Swagger Codegen in local Meetups or conferences +- actively answers questions from others in [Github](https://github.com/swagger-api/swagger-codegen/issues), [StackOverflow](stackoverflow.com/search?q=%5Bswagger%5D) +- submits PRs to improve Swagger Codegen +- reviews PRs submitted by the others +- ranks within top 100 in the [contributor list](https://github.com/swagger-api/swagger-codegen/graphs/contributors) + +If you want to be a Swagger Codegen Evangelist, please kindly apply by sending an email to wing328hk@gmail.com (@wing328) + +# License information on Generated Code The Swagger Codegen project is intended as a benefit for users of the Swagger / Open API Specification. The project itself has the [License](#license) as specified. In addition, please understand the following points: From c6aea46fa0197024b218d1d489b2cc36a865db6f Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Nov 2016 18:30:30 +0800 Subject: [PATCH 116/269] fix import in sample code (dart) (#4292) --- .../src/main/resources/dart/api_doc.mustache | 3 +-- .../client/petstore/dart/swagger/README.md | 2 +- .../petstore/dart/swagger/docs/PetApi.md | 24 +++++++------------ .../petstore/dart/swagger/docs/StoreApi.md | 12 ++++------ .../petstore/dart/swagger/docs/UserApi.md | 24 +++++++------------ 5 files changed, 22 insertions(+), 43 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache b/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache index 06491380ae8..e723114f18c 100644 --- a/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/dart/api_doc.mustache @@ -24,8 +24,7 @@ Method | HTTP request | Description ### Example ```dart -import '{{pubName}}.api'; -import '{{pubName}}.model'; +import 'package:{{pubName}}/api.dart'; {{#hasAuthMethods}} {{#authMethods}} {{#isBasic}} diff --git a/samples/client/petstore/dart/swagger/README.md b/samples/client/petstore/dart/swagger/README.md index 4eb573e3d32..92fa3e33024 100644 --- a/samples/client/petstore/dart/swagger/README.md +++ b/samples/client/petstore/dart/swagger/README.md @@ -4,7 +4,7 @@ This is a sample server Petstore server. You can find out more about Swagger at This Dart package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build date: 2016-11-30T17:17:22.024+08:00 +- Build date: 2016-11-30T18:12:21.701+08:00 - Build package: class io.swagger.codegen.languages.DartClientCodegen ## Requirements diff --git a/samples/client/petstore/dart/swagger/docs/PetApi.md b/samples/client/petstore/dart/swagger/docs/PetApi.md index 310ea9ee57b..04b6695dbd6 100644 --- a/samples/client/petstore/dart/swagger/docs/PetApi.md +++ b/samples/client/petstore/dart/swagger/docs/PetApi.md @@ -28,8 +28,7 @@ Add a new pet to the store ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -73,8 +72,7 @@ Deletes a pet ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -120,8 +118,7 @@ Multiple status values can be provided with comma separated strings ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -166,8 +163,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -212,8 +208,7 @@ Returns a single pet ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure API key authorization: api_key //swagger.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed @@ -260,8 +255,7 @@ Update an existing pet ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -305,8 +299,7 @@ Updates a pet in the store with form data ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; @@ -354,8 +347,7 @@ uploads an image ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure OAuth2 access token for authorization: petstore_auth //swagger.api.Configuration.accessToken = 'YOUR_ACCESS_TOKEN'; diff --git a/samples/client/petstore/dart/swagger/docs/StoreApi.md b/samples/client/petstore/dart/swagger/docs/StoreApi.md index a51bfe07cfc..112ffe75efb 100644 --- a/samples/client/petstore/dart/swagger/docs/StoreApi.md +++ b/samples/client/petstore/dart/swagger/docs/StoreApi.md @@ -24,8 +24,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new StoreApi(); var orderId = orderId_example; // String | ID of the order that needs to be deleted @@ -67,8 +66,7 @@ Returns a map of status codes to quantities ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; // TODO Configure API key authorization: api_key //swagger.api.Configuration.apiKey{'api_key'} = 'YOUR_API_KEY'; // uncomment below to setup prefix (e.g. Bearer) for API key, if needed @@ -111,8 +109,7 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new StoreApi(); var orderId = 789; // int | ID of pet that needs to be fetched @@ -155,8 +152,7 @@ Place an order for a pet ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new StoreApi(); var body = new Order(); // Order | order placed for purchasing the pet diff --git a/samples/client/petstore/dart/swagger/docs/UserApi.md b/samples/client/petstore/dart/swagger/docs/UserApi.md index bc26daaa1d1..8457602024a 100644 --- a/samples/client/petstore/dart/swagger/docs/UserApi.md +++ b/samples/client/petstore/dart/swagger/docs/UserApi.md @@ -28,8 +28,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var body = new User(); // User | Created user object @@ -71,8 +70,7 @@ Creates list of users with given input array ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var body = [new List<User>()]; // List | List of user object @@ -114,8 +112,7 @@ Creates list of users with given input array ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var body = [new List<User>()]; // List | List of user object @@ -157,8 +154,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var username = username_example; // String | The name that needs to be deleted @@ -200,8 +196,7 @@ Get user by user name ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var username = username_example; // String | The name that needs to be fetched. Use user1 for testing. @@ -244,8 +239,7 @@ Logs user into the system ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var username = username_example; // String | The user name for login @@ -290,8 +284,7 @@ Logs out current logged in user session ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); @@ -329,8 +322,7 @@ This can only be done by the logged in user. ### Example ```dart -import 'swagger.api'; -import 'swagger.model'; +import 'package:swagger/api.dart'; var api_instance = new UserApi(); var username = username_example; // String | name that need to be deleted From 9bd685dfe4bf44eac37856ee99540e7010b20163 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Nov 2016 23:31:21 +0800 Subject: [PATCH 117/269] add davidkiss as template creator --- README.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 646323bc220..86b450f24d2 100644 --- a/README.md +++ b/README.md @@ -875,15 +875,17 @@ Here is a list of template creators: * C++ REST: @Danielku15 * C# (.NET 2.0): @who * Clojure: @xhh - * Dart: @yissachar - * Groovy: @victorgit - * Go: @wing328 + * Dart: @yissachar + * Groovy: @victorgit + * Go: @wing328 + * Java (Feign): @davidkiss * Java (Retrofit): @0legg * Java (Retrofi2): @emilianobonassi * Java (Jersey2): @xhh * Java (okhttp-gson): @xhh - * Javascript/NodeJS: @jfiala + * Javascript/NodeJS: @jfiala * Javascript (Closure-annotated Angular) @achew22 + * JMeter @davidkiss * Perl: @wing328 * Swift: @tkqubo * Swift 3: @hexelon From 12c75a92250c2ff6c8e0e10b85ebcc45a3994921 Mon Sep 17 00:00:00 2001 From: Alan Renouf Date: Wed, 30 Nov 2016 11:26:47 -0800 Subject: [PATCH 118/269] Added VMware to list of Companies Added VMware to list of Companies using Swagger Codegen --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 86b450f24d2..a0624137a72 100644 --- a/README.md +++ b/README.md @@ -815,6 +815,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [TaskData](http://www.taskdata.com/) - [ThoughtWorks](https://www.thoughtworks.com) - [uShip](https://www.uship.com/) +- [VMware](https://vmware.com/) - [W.UP](http://wup.hu/?siteLang=en) - [Wealthfront](https://www.wealthfront.com/) - [WEXO A/S](https://www.wexo.dk/) From 0a97b9c5681c28808dd9af730b7611a6930e2a15 Mon Sep 17 00:00:00 2001 From: jaz-ah Date: Wed, 30 Nov 2016 19:49:56 -0800 Subject: [PATCH 119/269] make sure to camelize properly before checking for reserved words (#4302) --- .../codegen/languages/Swift3Codegen.java | 18 +++++++++++++----- .../codegen/swift3/Swift3CodegenTest.java | 10 ++++++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index dfa7bd60a4b..95dd23e0e15 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -518,25 +518,33 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); } + // Camelize only when we have a structure defined below + Boolean camelized = false; + if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { + name = camelize(name, true); + camelized = true; + } + // Reserved Name if (isReservedWord(name)) { return escapeReservedWord(name); } + // Check for numerical conversions if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { String varName = "number" + camelize(name); varName = varName.replaceAll("-", "minus"); varName = varName.replaceAll("\\+", "plus"); varName = varName.replaceAll("\\.", "dot"); - return varName; } - // Prevent from breaking properly cased identifier - if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { - return camelize(name, true); - } + // If we have already camelized the word, don't progress + // any further + if (camelized) { + return name; + } char[] separators = {'-', '_', ' ', ':', '(', ')'}; return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java index b0608b79b59..b933b064bb5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java @@ -13,6 +13,16 @@ public class Swift3CodegenTest { Swift3Codegen swiftCodegen = new Swift3Codegen(); + @Test + public void testReservedWord() throws Exception { + Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public"); + } + + @Test + public void shouldNotBreakNonReservedWord() throws Exception { + Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error"); + } + @Test public void shouldNotBreakCorrectName() throws Exception { Assert.assertEquals(swiftCodegen.toEnumVarName("EntryName", null), "entryName"); From af0d217c3812a23eb58aad07232c12152baf5e6a Mon Sep 17 00:00:00 2001 From: Sreenidhi Sreesha Date: Wed, 30 Nov 2016 23:46:44 -0800 Subject: [PATCH 120/269] Fix basePath set to null when generating API files. (#4304) --- .../io/swagger/codegen/DefaultGenerator.java | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b97c562a1a8..e3aee70a1b2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -78,18 +78,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { generateApis = System.getProperty("apis") != null ? true:null; generateModels = System.getProperty("models") != null ? true: null; generateSupportingFiles = System.getProperty("supportingFiles") != null ? true:null; - // model/api tests and documentation options rely on parent generate options (api or model) and no other options. - // They default to true in all scenarios and can only be marked false explicitly - generateModelTests = System.getProperty("modelTests") != null ? Boolean.valueOf(System.getProperty("modelTests")): true; - generateModelDocumentation = System.getProperty("modelDocs") != null ? Boolean.valueOf(System.getProperty("modelDocs")):true; - generateApiTests = System.getProperty("apiTests") != null ? Boolean.valueOf(System.getProperty("apiTests")): true; - generateApiDocumentation = System.getProperty("apiDocs") != null ? Boolean.valueOf(System.getProperty("apiDocs")):true; - if(generateApis == null && generateModels == null && generateSupportingFiles == null) { + if (generateApis == null && generateModels == null && generateSupportingFiles == null) { // no specifics are set, generate everything generateApis = generateModels = generateSupportingFiles = true; - } - else { + } else { if(generateApis == null) { generateApis = false; } @@ -100,6 +93,14 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { generateSupportingFiles = false; } } + // model/api tests and documentation options rely on parent generate options (api or model) and no other options. + // They default to true in all scenarios and can only be marked false explicitly + generateModelTests = System.getProperty("modelTests") != null ? Boolean.valueOf(System.getProperty("modelTests")): true; + generateModelDocumentation = System.getProperty("modelDocs") != null ? Boolean.valueOf(System.getProperty("modelDocs")):true; + generateApiTests = System.getProperty("apiTests") != null ? Boolean.valueOf(System.getProperty("apiTests")): true; + generateApiDocumentation = System.getProperty("apiDocs") != null ? Boolean.valueOf(System.getProperty("apiDocs")):true; + + // Additional properties added for tests to exclude references in project related files config.additionalProperties().put(CodegenConstants.GENERATE_API_TESTS, generateApiTests); config.additionalProperties().put(CodegenConstants.GENERATE_MODEL_TESTS, generateModelTests); @@ -117,6 +118,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (swagger.getVendorExtensions() != null) { config.vendorExtensions().putAll(swagger.getVendorExtensions()); } + + contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath()); + basePath = config.escapeText(getHost()); + basePathWithoutHost = config.escapeText(swagger.getBasePath()); + } private void configureSwaggerInfo() { @@ -581,9 +587,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (swagger.getHost() != null) { bundle.put("host", swagger.getHost()); } - contextPath = config.escapeText(swagger.getBasePath() == null ? "" : swagger.getBasePath()); - basePath = config.escapeText(getHost()); - basePathWithoutHost = config.escapeText(swagger.getBasePath()); + bundle.put("swagger", this.swagger); bundle.put("basePath", basePath); bundle.put("basePathWithoutHost",basePathWithoutHost); From 564e061da629dc84159849828314b04c595e31ad Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 1 Dec 2016 17:34:38 +0800 Subject: [PATCH 121/269] add Object as reserved keyword in Android --- .../io/swagger/codegen/languages/AndroidClientCodegen.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index e4dacc499bb..5f08cebcdf9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -54,6 +54,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi "localVarFormParams", "localVarContentTypes", "localVarContentType", "localVarResponse", "localVarBuilder", "authNames", "basePath", "apiInvoker", + // due to namespace collusion + "Object", + // android reserved words "abstract", "continue", "for", "new", "switch", "assert", "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", From 87cb779fd465a0ba50cfd55684ed56fe7bbcddd8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 1 Dec 2016 19:09:22 +0800 Subject: [PATCH 122/269] [Typscript][Angular2] Remove tab in TS Angular2 template (#4294) * remove tab in ts angular2 template * update petstore sample after basing on master --- .../resources/typescript-angular2/api.mustache | 8 ++++---- .../typescript-angular2/default/api/PetApi.ts | 14 +++++++------- .../typescript-angular2/default/api/StoreApi.ts | 4 ++-- .../typescript-angular2/default/api/UserApi.ts | 4 ++-- .../petstore/typescript-angular2/npm/README.md | 4 ++-- .../petstore/typescript-angular2/npm/api/PetApi.ts | 14 +++++++------- .../typescript-angular2/npm/api/StoreApi.ts | 4 ++-- .../typescript-angular2/npm/api/UserApi.ts | 4 ++-- .../petstore/typescript-angular2/npm/package.json | 2 +- 9 files changed, 29 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index fe745f03b10..cff9a078f65 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -22,7 +22,7 @@ import { Configuration } from '../configurat {{/description}} @Injectable() export class {{classname}} { - protected basePath = '{{basePath}}'; + protected basePath = '{{{basePath}}}'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); @@ -34,8 +34,8 @@ export class {{classname}} { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended @@ -185,4 +185,4 @@ export class {{classname}} { {{/operation}} } -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index b2feacfc4e1..ae42240256f 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -39,8 +39,8 @@ export class PetApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended @@ -414,17 +414,17 @@ export class PetApi { 'application/xml' ]; + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index b3d6ea61e60..484d5e56fde 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -39,8 +39,8 @@ export class StoreApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 25f38a899a4..8dda0cf8377 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -39,8 +39,8 @@ export class UserApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index bcf578d1297..578fb3165a2 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611201817 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612011557 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201611201817 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612011557 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index b2feacfc4e1..ae42240256f 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -39,8 +39,8 @@ export class PetApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended @@ -414,17 +414,17 @@ export class PetApi { 'application/xml' ]; + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index b3d6ea61e60..484d5e56fde 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -39,8 +39,8 @@ export class StoreApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 25f38a899a4..8dda0cf8377 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -39,8 +39,8 @@ export class UserApi { this.configuration = configuration; } } - - /** + + /** * * Extends object by coping non-existing properties. * @param objA object to be extended diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 5f09b8f7a0f..30cd1eb0801 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201611201817", + "version": "0.0.1-SNAPSHOT.201612011557", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 31d31b94665245509656457b219aba58d20009ac Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 2 Dec 2016 17:22:46 +0800 Subject: [PATCH 123/269] [Ruby] use hasConsumes, hasProduces in ruby client (#4310) * use hasConsumes, hasProduces in ruby client * add new ruby files --- .../src/main/resources/ruby/api.mustache | 12 +- samples/client/petstore/ruby/README.md | 2 + .../client/petstore/ruby/docs/ClassModel.md | 8 + samples/client/petstore/ruby/docs/EnumTest.md | 1 + .../client/petstore/ruby/docs/OuterEnum.md | 7 + samples/client/petstore/ruby/lib/petstore.rb | 2 + .../ruby/lib/petstore/api/fake_api.rb | 24 +-- .../petstore/ruby/lib/petstore/api/pet_api.rb | 64 ++---- .../ruby/lib/petstore/api/store_api.rb | 32 +-- .../ruby/lib/petstore/api/user_api.rb | 64 +----- .../ruby/lib/petstore/models/class_model.rb | 187 ++++++++++++++++++ .../ruby/lib/petstore/models/enum_test.rb | 17 +- .../ruby/lib/petstore/models/outer_enum.rb | 22 +++ .../ruby/spec/models/class_model_spec.rb | 41 ++++ .../ruby/spec/models/outer_enum_spec.rb | 35 ++++ 15 files changed, 354 insertions(+), 164 deletions(-) create mode 100644 samples/client/petstore/ruby/docs/ClassModel.md create mode 100644 samples/client/petstore/ruby/docs/OuterEnum.md create mode 100644 samples/client/petstore/ruby/lib/petstore/models/class_model.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb create mode 100644 samples/client/petstore/ruby/spec/models/class_model_spec.rb create mode 100644 samples/client/petstore/ruby/spec/models/outer_enum_spec.rb diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 8366246f467..faf2562fde9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -125,14 +125,14 @@ module {{moduleName}} # header parameters header_params = {} - + {{#hasProduces}} # HTTP header 'Accept' (if needed) - local_header_accept = [{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) + {{/hasProduces}} + {{#hasConsumes}} # HTTP header 'Content-Type' - local_header_content_type = [{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + {{/hasConsumes}} {{#headerParams}} {{#required}} header_params[:'{{{baseName}}}'] = {{#collectionFormat}}@api_client.build_collection_param({{{paramName}}}, :{{{collectionFormat}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}{{/collectionFormat}} diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 188335045f6..090cbc360c9 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -111,6 +111,7 @@ Class | Method | HTTP request | Description - [Petstore::ArrayTest](docs/ArrayTest.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) + - [Petstore::ClassModel](docs/ClassModel.md) - [Petstore::Client](docs/Client.md) - [Petstore::Dog](docs/Dog.md) - [Petstore::EnumArrays](docs/EnumArrays.md) @@ -126,6 +127,7 @@ Class | Method | HTTP request | Description - [Petstore::Name](docs/Name.md) - [Petstore::NumberOnly](docs/NumberOnly.md) - [Petstore::Order](docs/Order.md) + - [Petstore::OuterEnum](docs/OuterEnum.md) - [Petstore::Pet](docs/Pet.md) - [Petstore::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Petstore::SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/ruby/docs/ClassModel.md b/samples/client/petstore/ruby/docs/ClassModel.md new file mode 100644 index 00000000000..cd4de850633 --- /dev/null +++ b/samples/client/petstore/ruby/docs/ClassModel.md @@ -0,0 +1,8 @@ +# Petstore::ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/EnumTest.md b/samples/client/petstore/ruby/docs/EnumTest.md index ad3ee5c31bb..5ca83b3f77d 100644 --- a/samples/client/petstore/ruby/docs/EnumTest.md +++ b/samples/client/petstore/ruby/docs/EnumTest.md @@ -6,5 +6,6 @@ Name | Type | Description | Notes **enum_string** | **String** | | [optional] **enum_integer** | **Integer** | | [optional] **enum_number** | **Float** | | [optional] +**outer_enum** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/client/petstore/ruby/docs/OuterEnum.md b/samples/client/petstore/ruby/docs/OuterEnum.md new file mode 100644 index 00000000000..60d87c12381 --- /dev/null +++ b/samples/client/petstore/ruby/docs/OuterEnum.md @@ -0,0 +1,7 @@ +# Petstore::OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 739bdb85586..6999fac514b 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -25,6 +25,7 @@ require 'petstore/models/array_of_number_only' require 'petstore/models/array_test' require 'petstore/models/cat' require 'petstore/models/category' +require 'petstore/models/class_model' require 'petstore/models/client' require 'petstore/models/dog' require 'petstore/models/enum_arrays' @@ -40,6 +41,7 @@ require 'petstore/models/model_return' require 'petstore/models/name' require 'petstore/models/number_only' require 'petstore/models/order' +require 'petstore/models/outer_enum' require 'petstore/models/pet' require 'petstore/models/read_only_first' require 'petstore/models/special_model_name' diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 1e32ef1694a..f48b77f7c2b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -48,14 +48,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' - local_header_content_type = ['application/json'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json']) # form parameters form_params = {} @@ -189,14 +185,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # HTTP header 'Content-Type' - local_header_content_type = ['application/xml; charset=utf-8', 'application/json; charset=utf-8'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) # form parameters form_params = {} @@ -292,14 +284,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['*/*'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['*/*']) # HTTP header 'Content-Type' - local_header_content_type = ['*/*'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['*/*']) header_params[:'enum_header_string_array'] = @api_client.build_collection_param(opts[:'enum_header_string_array'], :csv) if !opts[:'enum_header_string_array'].nil? header_params[:'enum_header_string'] = opts[:'enum_header_string'] if !opts[:'enum_header_string'].nil? diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 58f4591d8eb..f6ca76d10b0 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -48,14 +48,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # HTTP header 'Content-Type' - local_header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} @@ -106,14 +102,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) header_params[:'api_key'] = opts[:'api_key'] if !opts[:'api_key'].nil? # form parameters @@ -164,14 +154,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -222,14 +206,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -279,14 +257,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -336,14 +308,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # HTTP header 'Content-Type' - local_header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/json', 'application/xml']) # form parameters form_params = {} @@ -396,14 +364,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # HTTP header 'Content-Type' - local_header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) # form parameters form_params = {} @@ -458,14 +422,10 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - + header_params['Accept'] = @api_client.select_header_accept(['application/json']) # HTTP header 'Content-Type' - local_header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(['multipart/form-data']) # form parameters form_params = {} diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index d2a01ef8346..4f0e12c2ef0 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -52,14 +52,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -104,14 +98,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) # form parameters form_params = {} @@ -169,14 +157,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -226,14 +208,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 15c2dd9e0c0..30766994678 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -48,14 +48,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -104,14 +98,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -160,14 +148,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -216,14 +198,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -272,14 +248,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -335,14 +305,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -388,14 +352,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} @@ -448,14 +406,8 @@ module Petstore # header parameters header_params = {} - # HTTP header 'Accept' (if needed) - local_header_accept = ['application/xml', 'application/json'] - local_header_accept_result = @api_client.select_header_accept(local_header_accept) and header_params['Accept'] = local_header_accept_result - - # HTTP header 'Content-Type' - local_header_content_type = [] - header_params['Content-Type'] = @api_client.select_header_content_type(local_header_content_type) + header_params['Accept'] = @api_client.select_header_accept(['application/xml', 'application/json']) # form parameters form_params = {} diff --git a/samples/client/petstore/ruby/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb new file mode 100644 index 00000000000..af91668e1f3 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb @@ -0,0 +1,187 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'date' + +module Petstore + # Model for testing model with \"_class\" property + class ClassModel + attr_accessor :_class + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'_class' => :'_class' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'_class' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'_class') + self._class = attributes[:'_class'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + _class == o._class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [_class].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index 62784d7d45a..d8efd0acd22 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -20,6 +20,8 @@ module Petstore attr_accessor :enum_number + attr_accessor :outer_enum + class EnumAttributeValidator attr_reader :datatype attr_reader :allowable_values @@ -47,7 +49,8 @@ module Petstore { :'enum_string' => :'enum_string', :'enum_integer' => :'enum_integer', - :'enum_number' => :'enum_number' + :'enum_number' => :'enum_number', + :'outer_enum' => :'outerEnum' } end @@ -56,7 +59,8 @@ module Petstore { :'enum_string' => :'String', :'enum_integer' => :'Integer', - :'enum_number' => :'Float' + :'enum_number' => :'Float', + :'outer_enum' => :'OuterEnum' } end @@ -80,6 +84,10 @@ module Petstore self.enum_number = attributes[:'enum_number'] end + if attributes.has_key?(:'outerEnum') + self.outer_enum = attributes[:'outerEnum'] + end + end # Show invalid properties with the reasons. Usually used together with valid? @@ -138,7 +146,8 @@ module Petstore self.class == o.class && enum_string == o.enum_string && enum_integer == o.enum_integer && - enum_number == o.enum_number + enum_number == o.enum_number && + outer_enum == o.outer_enum end # @see the `==` method @@ -150,7 +159,7 @@ module Petstore # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash - [enum_string, enum_integer, enum_number].hash + [enum_string, enum_integer, enum_number, outer_enum].hash end # Builds the object from hash diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb new file mode 100644 index 00000000000..4d7de6c694a --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb @@ -0,0 +1,22 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'date' + +module Petstore + class OuterEnum + + PLACED = "placed".freeze + APPROVED = "approved".freeze + DELIVERED = "delivered".freeze + end + +end diff --git a/samples/client/petstore/ruby/spec/models/class_model_spec.rb b/samples/client/petstore/ruby/spec/models/class_model_spec.rb new file mode 100644 index 00000000000..12560311a6c --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/class_model_spec.rb @@ -0,0 +1,41 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::ClassModel +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'ClassModel' do + before do + # run before each test + @instance = Petstore::ClassModel.new + end + + after do + # run after each test + end + + describe 'test an instance of ClassModel' do + it 'should create an instact of ClassModel' do + expect(@instance).to be_instance_of(Petstore::ClassModel) + end + end + describe 'test attribute "_class"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb b/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb new file mode 100644 index 00000000000..0eae1f6a95f --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/outer_enum_spec.rb @@ -0,0 +1,35 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::OuterEnum +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'OuterEnum' do + before do + # run before each test + @instance = Petstore::OuterEnum.new + end + + after do + # run after each test + end + + describe 'test an instance of OuterEnum' do + it 'should create an instact of OuterEnum' do + expect(@instance).to be_instance_of(Petstore::OuterEnum) + end + end +end + From 18420dd7f95cc5648c25b46ebd42a85423f1c351 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 2 Dec 2016 17:59:35 +0800 Subject: [PATCH 124/269] add serialVersionUID to java model (#4311) --- modules/swagger-codegen/src/main/resources/Java/pojo.mustache | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index c522bdba860..a76452fddc8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -4,6 +4,10 @@ @ApiModel(description = "{{{description}}}"){{/description}} {{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}} public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcelableModel}}implements Parcelable {{#serializableModel}}, Serializable {{/serializableModel}}{{/parcelableModel}}{{^parcelableModel}}{{#serializableModel}}implements Serializable {{/serializableModel}}{{/parcelableModel}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} {{#vars}} {{#isEnum}} {{^isContainer}} From 964a9a96963d7ae44f2fff395e18a517903f326d Mon Sep 17 00:00:00 2001 From: Samuel Beliveau Date: Fri, 2 Dec 2016 10:24:32 -0500 Subject: [PATCH 125/269] Support for standalone enums in Typescript-Angular2 Improved typescript primitive detection for tagging type with models namespace --- .../AbstractTypeScriptClientCodegen.java | 6 ++++ .../TypeScriptAngular2ClientCodegen.java | 14 +++++--- .../typescript-angular2/model.mustache | 33 ++----------------- .../typescript-angular2/modelEnum.mustache | 12 +++++++ .../typescript-angular2/modelGeneric.mustache | 28 ++++++++++++++++ .../typescript-angular2/default/api/PetApi.ts | 2 +- .../default/api/StoreApi.ts | 2 +- .../default/api/UserApi.ts | 2 +- 8 files changed, 60 insertions(+), 39 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/typescript-angular2/modelEnum.mustache create mode 100644 modules/swagger-codegen/src/main/resources/typescript-angular2/modelGeneric.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 9322af82e95..e1b05af4ebb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -26,6 +26,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp protected String modelPropertyNaming= "camelCase"; protected Boolean supportsES6 = true; + protected HashSet languageGenericTypes; public AbstractTypeScriptClientCodegen() { super(); @@ -58,6 +59,11 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp "any", "Error" )); + + languageGenericTypes = new HashSet(Arrays.asList( + "Array" + )); + instantiationTypes.put("array", "Array"); typeMapping = new HashMap(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java index aeb5d774add..91ed4f35f86 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngular2ClientCodegen.java @@ -132,7 +132,7 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); - if(languageSpecificPrimitives.contains(swaggerType)) { + if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { return swaggerType; } return addModelPrefix(swaggerType); @@ -146,15 +146,19 @@ public class TypeScriptAngular2ClientCodegen extends AbstractTypeScriptClientCod type = swaggerType; } - if (!startsWithLanguageSpecificPrimitiv(type)) { + if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) { type = "models." + swaggerType; } return type; } - private boolean startsWithLanguageSpecificPrimitiv(String type) { - for (String langPrimitive:languageSpecificPrimitives) { - if (type.startsWith(langPrimitive)) { + private boolean isLanguagePrimitive(String type) { + return languageSpecificPrimitives.contains(type); + } + + private boolean isLanguageGenericType(String type) { + for (String genericType: languageGenericTypes) { + if (type.startsWith(genericType + "<")) { return true; } } diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache index d0e544c4e2f..410810763d8 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/model.mustache @@ -8,35 +8,6 @@ import * as models from './models'; * {{{description}}} */ {{/description}} -export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{ -{{#additionalPropertiesType}} - [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; - -{{/additionalPropertiesType}} -{{#vars}} -{{#description}} - /** - * {{{description}}} - */ -{{/description}} - {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; - -{{/vars}} -} -{{#hasEnums}} -export namespace {{classname}} { -{{#vars}} -{{#isEnum}} - export enum {{enumName}} { - {{#allowableValues}} - {{#enumVars}} - {{{name}}} = {{{value}}}{{^-last}},{{/-last}} - {{/enumVars}} - {{/allowableValues}} - } -{{/isEnum}} -{{/vars}} -} -{{/hasEnums}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{>modelGeneric}}{{/isEnum}} {{/model}} -{{/models}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/modelEnum.mustache new file mode 100644 index 00000000000..47886484118 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/modelEnum.mustache @@ -0,0 +1,12 @@ +{{#description}} + /** + * {{{description}}} + */ +{{/description}} +export enum {{classname}} { +{{#allowableValues}} +{{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/modelGeneric.mustache new file mode 100644 index 00000000000..fbe96c21506 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/modelGeneric.mustache @@ -0,0 +1,28 @@ +export interface {{classname}} {{#parent}}extends models.{{{parent}}} {{/parent}}{ +{{#additionalPropertiesType}} + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; + +{{/additionalPropertiesType}} +{{#vars}} + {{#description}} + /** + * {{{description}}} + */ + {{/description}} + {{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; + +{{/vars}} +}{{#hasEnums}} +export namespace {{classname}} { +{{#vars}} + {{#isEnum}} + export enum {{enumName}} { + {{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } + {{/isEnum}} +{{/vars}} +}{{/hasEnums}} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index b2feacfc4e1..d6b62cbdd47 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = ''; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index b3d6ea61e60..4180f1bd5f7 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = ''; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 25f38a899a4..b0ab2101ff9 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; + protected basePath = ''; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); From 2b240a4eb93b9a97d2a8d6ec5f31f0153fb6793d Mon Sep 17 00:00:00 2001 From: Alec Henninger Date: Sun, 4 Dec 2016 21:56:03 -0500 Subject: [PATCH 126/269] Use JavaScript codegen in JavaScript test (instead of Java) (#4316) --- .../io/swagger/codegen/javascript/JavaScriptModelEnumTest.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java index e87c78e78ba..4ef973b7df7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -3,7 +3,6 @@ package io.swagger.codegen.javascript; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.languages.JavaClientCodegen; import io.swagger.codegen.languages.JavascriptClientCodegen; import io.swagger.models.ComposedModel; import io.swagger.models.Model; @@ -74,7 +73,7 @@ public class JavaScriptModelEnumTest { .child(subModel) .interfaces(new ArrayList()); - final DefaultCodegen codegen = new JavaClientCodegen(); + final DefaultCodegen codegen = new JavascriptClientCodegen(); final Map allModels = new HashMap(); allModels.put(parentModel.getName(), parentModel); allModels.put(subModel.getName(), subModel); From 79a71fd6978540626fbfe62d89ec9dbbb23e5fb0 Mon Sep 17 00:00:00 2001 From: Tadhg Pearson Date: Mon, 5 Dec 2016 04:34:37 -0500 Subject: [PATCH 127/269] Update docs for Java code generation (#4303) * Updated documentation to support Java code generation * Tabs to spaces in example pom --- README.md | 4 +- .../examples/java-client.xml | 86 +++++++++++-------- 2 files changed, 50 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index a0624137a72..a2b40c7f8ff 100644 --- a/README.md +++ b/README.md @@ -552,10 +552,10 @@ CONFIG OPTIONS library library template (sub-template) to use: - - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 + jersey1 - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 feign - HTTP client: Netflix Feign 8.1.1. JSON processing: Jackson 2.6.3 - okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 + okhttp-gson (default) - 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) ``` diff --git a/modules/swagger-codegen-maven-plugin/examples/java-client.xml b/modules/swagger-codegen-maven-plugin/examples/java-client.xml index b14c33e9424..04eb13a8310 100644 --- a/modules/swagger-codegen-maven-plugin/examples/java-client.xml +++ b/modules/swagger-codegen-maven-plugin/examples/java-client.xml @@ -27,7 +27,7 @@ - java8 + joda @@ -39,17 +39,26 @@ - + + - io.swagger - swagger-annotations - ${swagger-annotations-version} + io.swagger + swagger-annotations + ${swagger-annotations-version} + + - org.glassfish.jersey.core - jersey-client + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson ${jersey-version} @@ -57,58 +66,59 @@ jersey-media-multipart ${jersey-version} - - org.glassfish.jersey.media - jersey-media-json-jackson - 2.22.1 - - com.fasterxml.jackson.core - jackson-core + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base ${jackson-version} - com.fasterxml.jackson.core - jackson-annotations - ${jackson-version} + com.fasterxml.jackson.core + jackson-core + ${jackson-version} - com.fasterxml.jackson.core - jackson-databind - ${jackson-version} + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} - com.fasterxml.jackson.datatype - jackson-datatype-joda - 2.1.5 + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} - joda-time - joda-time - ${jodatime-version} + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + joda-time + joda-time + ${jodatime-version} + com.brsanthu migbase64 2.2 - - - - junit - junit - ${junit-version} - test - + + - 1.5.0 - 2.12 - 2.4.2 - 2.3 + 1.5.8 + 2.22.2 + 2.7.0 + 2.7 1.0.0 4.8.1 From 648f8df2353a475bd20bdf418779367267cbe5dc Mon Sep 17 00:00:00 2001 From: Sebastian Haas Date: Tue, 6 Dec 2016 16:59:59 +0100 Subject: [PATCH 128/269] Fix for missing headers (#4328) * Fix for #4322 Signed-off-by: Sebastian Haas * Run typescript-angular2-petstore.sh Signed-off-by: Sebastian Haas * Run typescript-angular2-petstore.sh Signed-off-by: Sebastian Haas --- .../src/main/resources/typescript-angular2/api.mustache | 5 ++--- .../petstore/typescript-angular2/default/api/PetApi.ts | 1 + samples/client/petstore/typescript-angular2/npm/README.md | 4 ++-- .../client/petstore/typescript-angular2/npm/api/PetApi.ts | 1 + samples/client/petstore/typescript-angular2/npm/package.json | 2 +- 5 files changed, 7 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index cff9a078f65..6f085fe3411 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -98,10 +98,9 @@ export class {{classname}} { } {{/queryParams}} -{{#headers}} +{{#headerParams}} headers.set('{{baseName}}', String({{paramName}})); - -{{/headers}} +{{/headerParams}} // to determine the Content-Type header let consumes: string[] = [ diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index ae42240256f..70ab123c5a5 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -255,6 +255,7 @@ export class PetApi { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } + headers.set('api_key', String(apiKey)); // to determine the Content-Type header let consumes: string[] = [ diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 578fb3165a2..1c4f0c5bd4f 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612011557 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612011557 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index ae42240256f..70ab123c5a5 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -255,6 +255,7 @@ export class PetApi { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } + headers.set('api_key', String(apiKey)); // to determine the Content-Type header let consumes: string[] = [ diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 30cd1eb0801..eeeca81bcbb 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201612011557", + "version": "0.0.1-SNAPSHOT.201612061134", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 8e1eeaa737b7b9acfdf130d76a6e14578f29404f Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Tue, 6 Dec 2016 12:04:13 -0500 Subject: [PATCH 129/269] [csharp] Remove generatePropertyChanged when explicitly false (#4280) --- .../io/swagger/codegen/languages/CSharpClientCodegen.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 0dcaa6869b0..26df3d83e5c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -199,6 +199,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { } else { setGeneratePropertyChanged(Boolean.valueOf(additionalProperties.get(CodegenConstants.GENERATE_PROPERTY_CHANGED).toString())); } + + if(Boolean.FALSE.equals(this.generatePropertyChanged)) { + additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); + } } additionalProperties.put("targetFrameworkNuget", this.targetFrameworkNuget); From 8153f0e89bf776d5388ebe86e28239e994cbe19b Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 7 Dec 2016 16:46:41 +0800 Subject: [PATCH 130/269] Fix test spec issue (#4334) * fix issue with swagger spec (number => integer) * remove space from spec --- ...ith-fake-endpoints-models-for-testing.yaml | 2 +- .../petstore/php/SwaggerClient-php/README.md | 2 ++ .../SwaggerClient-php/docs/Model/EnumTest.md | 1 + .../lib/Model/AdditionalPropertiesClass.php | 1 + .../SwaggerClient-php/lib/Model/Animal.php | 1 + .../lib/Model/AnimalFarm.php | 1 + .../lib/Model/ApiResponse.php | 1 + .../lib/Model/ArrayOfArrayOfNumberOnly.php | 1 + .../lib/Model/ArrayOfNumberOnly.php | 1 + .../SwaggerClient-php/lib/Model/ArrayTest.php | 1 + .../php/SwaggerClient-php/lib/Model/Cat.php | 1 + .../SwaggerClient-php/lib/Model/Category.php | 1 + .../SwaggerClient-php/lib/Model/Client.php | 1 + .../php/SwaggerClient-php/lib/Model/Dog.php | 1 + .../lib/Model/EnumArrays.php | 1 + .../SwaggerClient-php/lib/Model/EnumTest.php | 35 ++++++++++++++++--- .../lib/Model/FormatTest.php | 1 + .../lib/Model/HasOnlyReadOnly.php | 1 + .../SwaggerClient-php/lib/Model/MapTest.php | 1 + ...PropertiesAndAdditionalPropertiesClass.php | 1 + .../lib/Model/Model200Response.php | 1 + .../SwaggerClient-php/lib/Model/ModelList.php | 1 + .../lib/Model/ModelReturn.php | 1 + .../php/SwaggerClient-php/lib/Model/Name.php | 1 + .../lib/Model/NumberOnly.php | 1 + .../php/SwaggerClient-php/lib/Model/Order.php | 1 + .../php/SwaggerClient-php/lib/Model/Pet.php | 1 + .../lib/Model/ReadOnlyFirst.php | 1 + .../lib/Model/SpecialModelName.php | 1 + .../php/SwaggerClient-php/lib/Model/Tag.php | 1 + .../php/SwaggerClient-php/lib/Model/User.php | 1 + samples/client/petstore/ruby/docs/FakeApi.md | 4 +-- .../ruby/lib/petstore/api/fake_api.rb | 4 +-- 33 files changed, 66 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index ea868cec98f..c7782a53be7 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -652,7 +652,7 @@ paths: in: query description: Query parameter enum test (string) - name: enum_query_integer - type: number + type: integer format: int32 enum: - 1 diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 6089d21da1c..068d01c9b10 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -111,6 +111,7 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/Model/ArrayTest.md) - [Cat](docs/Model/Cat.md) - [Category](docs/Model/Category.md) + - [ClassModel](docs/Model/ClassModel.md) - [Client](docs/Model/Client.md) - [Dog](docs/Model/Dog.md) - [EnumArrays](docs/Model/EnumArrays.md) @@ -126,6 +127,7 @@ Class | Method | HTTP request | Description - [Name](docs/Model/Name.md) - [NumberOnly](docs/Model/NumberOnly.md) - [Order](docs/Model/Order.md) + - [OuterEnum](docs/Model/OuterEnum.md) - [Pet](docs/Model/Pet.md) - [ReadOnlyFirst](docs/Model/ReadOnlyFirst.md) - [SpecialModelName](docs/Model/SpecialModelName.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md index 2ef9e6adaac..4d0f96c720f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **enum_string** | **string** | | [optional] **enum_integer** | **int** | | [optional] **enum_number** | **double** | | [optional] +**outer_enum** | [**\Swagger\Client\Model\OuterEnum**](OuterEnum.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 60c0799ecc3..5be00bdb3dc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -251,3 +251,4 @@ class AdditionalPropertiesClass implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index 06625475509..dff108c3214 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -261,3 +261,4 @@ class Animal implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index a814b227c14..b9244039c30 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -203,3 +203,4 @@ class AnimalFarm implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 1240d1f3efb..2d2732d89c8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -277,3 +277,4 @@ class ApiResponse implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 060c16dc443..eb969b9c1be 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -225,3 +225,4 @@ class ArrayOfArrayOfNumberOnly implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index eac1a959200..be0521157ff 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -225,3 +225,4 @@ class ArrayOfNumberOnly implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index e3266c65b0c..5eda007acef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -277,3 +277,4 @@ class ArrayTest implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index fbab168ade9..8450b99c1ea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -227,3 +227,4 @@ class Cat extends Animal implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index b3f6ffc1c7c..c5b1e6c96ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -251,3 +251,4 @@ class Category implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php index 55ef2a1918a..e642f6f8da9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -225,3 +225,4 @@ class Client implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index 2888805e717..a6a17e6114a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -227,3 +227,4 @@ class Dog extends Animal implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index c2bc15def85..e6dea8c2d18 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -296,3 +296,4 @@ class EnumArrays implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index b0ba03e5748..cfee4f5eaab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -57,7 +57,8 @@ class EnumTest implements ArrayAccess protected static $swaggerTypes = [ 'enum_string' => 'string', 'enum_integer' => 'int', - 'enum_number' => 'double' + 'enum_number' => 'double', + 'outer_enum' => '\Swagger\Client\Model\OuterEnum' ]; public static function swaggerTypes() @@ -72,7 +73,8 @@ class EnumTest implements ArrayAccess protected static $attributeMap = [ 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', - 'enum_number' => 'enum_number' + 'enum_number' => 'enum_number', + 'outer_enum' => 'outerEnum' ]; @@ -83,7 +85,8 @@ class EnumTest implements ArrayAccess protected static $setters = [ 'enum_string' => 'setEnumString', 'enum_integer' => 'setEnumInteger', - 'enum_number' => 'setEnumNumber' + 'enum_number' => 'setEnumNumber', + 'outer_enum' => 'setOuterEnum' ]; @@ -94,7 +97,8 @@ class EnumTest implements ArrayAccess protected static $getters = [ 'enum_string' => 'getEnumString', 'enum_integer' => 'getEnumInteger', - 'enum_number' => 'getEnumNumber' + 'enum_number' => 'getEnumNumber', + 'outer_enum' => 'getOuterEnum' ]; public static function attributeMap() @@ -173,6 +177,7 @@ class EnumTest implements ArrayAccess $this->container['enum_string'] = isset($data['enum_string']) ? $data['enum_string'] : null; $this->container['enum_integer'] = isset($data['enum_integer']) ? $data['enum_integer'] : null; $this->container['enum_number'] = isset($data['enum_number']) ? $data['enum_number'] : null; + $this->container['outer_enum'] = isset($data['outer_enum']) ? $data['outer_enum'] : null; } /** @@ -299,6 +304,27 @@ class EnumTest implements ArrayAccess return $this; } + + /** + * Gets outer_enum + * @return \Swagger\Client\Model\OuterEnum + */ + public function getOuterEnum() + { + return $this->container['outer_enum']; + } + + /** + * Sets outer_enum + * @param \Swagger\Client\Model\OuterEnum $outer_enum + * @return $this + */ + public function setOuterEnum($outer_enum) + { + $this->container['outer_enum'] = $outer_enum; + + return $this; + } /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset @@ -358,3 +384,4 @@ class EnumTest implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 72c8f79a357..524904f2af7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -704,3 +704,4 @@ class FormatTest implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index 6251620638f..c88fa186ccb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -251,3 +251,4 @@ class HasOnlyReadOnly implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index 986d9b1d81a..67c6f2ef6ff 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -269,3 +269,4 @@ class MapTest implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 8af27a9c528..232f6f161cf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -277,3 +277,4 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index d1d79f9fd6c..610ae374fd4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -252,3 +252,4 @@ class Model200Response implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php index d185af146f4..35789521a88 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -225,3 +225,4 @@ class ModelList implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 379acc123a6..2d65176ee55 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -226,3 +226,4 @@ class ModelReturn implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index 9722713dc26..eb45df9cacd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -310,3 +310,4 @@ class Name implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index 3603f9bdd9f..2907e80bee9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -225,3 +225,4 @@ class NumberOnly implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index a50b997b635..8a3e8b58ff4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -384,3 +384,4 @@ class Order implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index fe9f255f75c..95f0ab651be 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -396,3 +396,4 @@ class Pet implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index 838792fa0c1..1f2ec1095ab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -251,3 +251,4 @@ class ReadOnlyFirst implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index ad2e8394bc7..dc78d2ef6c5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -225,3 +225,4 @@ class SpecialModelName implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 29578f37802..f72c54d58bd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -251,3 +251,4 @@ class Tag implements ArrayAccess } } + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index ca36471adce..82564b9d658 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -407,3 +407,4 @@ class User implements ArrayAccess } } + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 971fdadb1ae..aca0fbd10d6 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -156,7 +156,7 @@ opts = { enum_header_string: "-efg", # String | Header parameter enum test (string) enum_query_string_array: ["enum_query_string_array_example"], # Array | Query parameter enum test (string array) enum_query_string: "-efg", # String | Query parameter enum test (string) - enum_query_integer: 3.4, # Float | Query parameter enum test (double) + enum_query_integer: 56, # Integer | Query parameter enum test (double) enum_query_double: 1.2 # Float | Query parameter enum test (double) } @@ -178,7 +178,7 @@ Name | Type | Description | Notes **enum_header_string** | **String**| Header parameter enum test (string) | [optional] [default to -efg] **enum_query_string_array** | [**Array<String>**](String.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **String**| Query parameter enum test (string) | [optional] [default to -efg] - **enum_query_integer** | **Float**| Query parameter enum test (double) | [optional] + **enum_query_integer** | **Integer**| Query parameter enum test (double) | [optional] **enum_query_double** | **Float**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index f48b77f7c2b..c5cdf4da1c9 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -231,7 +231,7 @@ module Petstore # @option opts [String] :enum_header_string Header parameter enum test (string) (default to -efg) # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) (default to -efg) - # @option opts [Float] :enum_query_integer Query parameter enum test (double) + # @option opts [Integer] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [nil] def test_enum_parameters(opts = {}) @@ -248,7 +248,7 @@ module Petstore # @option opts [String] :enum_header_string Header parameter enum test (string) # @option opts [Array] :enum_query_string_array Query parameter enum test (string array) # @option opts [String] :enum_query_string Query parameter enum test (string) - # @option opts [Float] :enum_query_integer Query parameter enum test (double) + # @option opts [Integer] :enum_query_integer Query parameter enum test (double) # @option opts [Float] :enum_query_double Query parameter enum test (double) # @return [Array<(nil, Fixnum, Hash)>] nil, response status code and response headers def test_enum_parameters_with_http_info(opts = {}) From b7984e55a71c6551633ef25d39dad2744d4623a1 Mon Sep 17 00:00:00 2001 From: Alvin Date: Wed, 7 Dec 2016 03:58:21 -0600 Subject: [PATCH 131/269] [Swift3][bug#4318] Bug when handling java date (#4332) * fix bug #4318 * swift3 samples update --- .../src/main/resources/swift3/Models.mustache | 5 +-- .../Classes/Swaggers/Models.swift | 35 +++++++++++++++++-- .../Classes/Swaggers/Models/EnumTest.swift | 2 ++ .../Classes/Swaggers/Models.swift | 35 +++++++++++++++++-- .../Classes/Swaggers/Models/EnumTest.swift | 2 ++ .../Classes/Swaggers/Models.swift | 35 +++++++++++++++++-- .../Classes/Swaggers/Models/EnumTest.swift | 2 ++ 7 files changed, 108 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift3/Models.mustache b/modules/swagger-codegen/src/main/resources/swift3/Models.mustache index db33865ad4a..19edf4da786 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/Models.mustache @@ -126,7 +126,8 @@ class Decoders { "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", - "yyyy-MM-dd'T'HH:mm:ss.SSS" + "yyyy-MM-dd'T'HH:mm:ss.SSS", + "yyyy-MM-dd HH:mm:ss" ].map { (format: String) -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = format @@ -141,7 +142,7 @@ class Decoders { } } } - if let sourceInt = source as? Int { + if let sourceInt = source as? Int64 { // treat as a java date return Date(timeIntervalSince1970: Double(sourceInt / 1000) ) } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift index cf0d7c99512..2757afd722d 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -126,7 +126,8 @@ class Decoders { "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", - "yyyy-MM-dd'T'HH:mm:ss.SSS" + "yyyy-MM-dd'T'HH:mm:ss.SSS", + "yyyy-MM-dd HH:mm:ss" ].map { (format: String) -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = format @@ -141,7 +142,7 @@ class Decoders { } } } - if let sourceInt = source as? Int { + if let sourceInt = source as? Int64 { // treat as a java date return Date(timeIntervalSince1970: Double(sourceInt / 1000) ) } @@ -284,6 +285,20 @@ class Decoders { } + // Decoder for [ClassModel] + Decoders.addDecoder(clazz: [ClassModel].self) { (source: AnyObject) -> [ClassModel] in + return Decoders.decode(clazz: [ClassModel].self, source: source) + } + // Decoder for ClassModel + Decoders.addDecoder(clazz: ClassModel.self) { (source: AnyObject) -> ClassModel in + let sourceDictionary = source as! [AnyHashable: Any] + + let instance = ClassModel() + instance._class = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["_class"] as AnyObject?) + return instance + } + + // Decoder for [Client] Decoders.addDecoder(clazz: [Client].self) { (source: AnyObject) -> [Client] in return Decoders.decode(clazz: [Client].self, source: source) @@ -371,6 +386,7 @@ class Decoders { instance.enumNumber = EnumTest.EnumNumber(rawValue: (enumNumber)) } + instance.outerEnum = Decoders.decodeOptional(clazz: OuterEnum.self, source: sourceDictionary["outerEnum"] as AnyObject?) return instance } @@ -531,6 +547,21 @@ class Decoders { } + // Decoder for [OuterEnum] + Decoders.addDecoder(clazz: [OuterEnum].self) { (source: AnyObject) -> [OuterEnum] in + return Decoders.decode(clazz: [OuterEnum].self, source: source) + } + // Decoder for OuterEnum + Decoders.addDecoder(clazz: OuterEnum.self) { (source: AnyObject) -> OuterEnum in + if let source = source as? String { + if let result = OuterEnum(rawValue: source) { + return result + } + } + fatalError("Source \(source) is not convertible to enum type OuterEnum: Maybe swagger file is insufficient") + } + + // Decoder for [Pet] Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in return Decoders.decode(clazz: [Pet].self, source: source) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 03342500961..b3be1c99858 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -24,6 +24,7 @@ open class EnumTest: JSONEncodable { public var enumString: EnumString? public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? public init() {} @@ -33,6 +34,7 @@ open class EnumTest: JSONEncodable { nillableDictionary["enum_string"] = self.enumString?.rawValue nillableDictionary["enum_integer"] = self.enumInteger?.rawValue nillableDictionary["enum_number"] = self.enumNumber?.rawValue + nillableDictionary["outerEnum"] = self.outerEnum?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index cf0d7c99512..2757afd722d 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -126,7 +126,8 @@ class Decoders { "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", - "yyyy-MM-dd'T'HH:mm:ss.SSS" + "yyyy-MM-dd'T'HH:mm:ss.SSS", + "yyyy-MM-dd HH:mm:ss" ].map { (format: String) -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = format @@ -141,7 +142,7 @@ class Decoders { } } } - if let sourceInt = source as? Int { + if let sourceInt = source as? Int64 { // treat as a java date return Date(timeIntervalSince1970: Double(sourceInt / 1000) ) } @@ -284,6 +285,20 @@ class Decoders { } + // Decoder for [ClassModel] + Decoders.addDecoder(clazz: [ClassModel].self) { (source: AnyObject) -> [ClassModel] in + return Decoders.decode(clazz: [ClassModel].self, source: source) + } + // Decoder for ClassModel + Decoders.addDecoder(clazz: ClassModel.self) { (source: AnyObject) -> ClassModel in + let sourceDictionary = source as! [AnyHashable: Any] + + let instance = ClassModel() + instance._class = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["_class"] as AnyObject?) + return instance + } + + // Decoder for [Client] Decoders.addDecoder(clazz: [Client].self) { (source: AnyObject) -> [Client] in return Decoders.decode(clazz: [Client].self, source: source) @@ -371,6 +386,7 @@ class Decoders { instance.enumNumber = EnumTest.EnumNumber(rawValue: (enumNumber)) } + instance.outerEnum = Decoders.decodeOptional(clazz: OuterEnum.self, source: sourceDictionary["outerEnum"] as AnyObject?) return instance } @@ -531,6 +547,21 @@ class Decoders { } + // Decoder for [OuterEnum] + Decoders.addDecoder(clazz: [OuterEnum].self) { (source: AnyObject) -> [OuterEnum] in + return Decoders.decode(clazz: [OuterEnum].self, source: source) + } + // Decoder for OuterEnum + Decoders.addDecoder(clazz: OuterEnum.self) { (source: AnyObject) -> OuterEnum in + if let source = source as? String { + if let result = OuterEnum(rawValue: source) { + return result + } + } + fatalError("Source \(source) is not convertible to enum type OuterEnum: Maybe swagger file is insufficient") + } + + // Decoder for [Pet] Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in return Decoders.decode(clazz: [Pet].self, source: source) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 03342500961..b3be1c99858 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -24,6 +24,7 @@ open class EnumTest: JSONEncodable { public var enumString: EnumString? public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? public init() {} @@ -33,6 +34,7 @@ open class EnumTest: JSONEncodable { nillableDictionary["enum_string"] = self.enumString?.rawValue nillableDictionary["enum_integer"] = self.enumInteger?.rawValue nillableDictionary["enum_number"] = self.enumNumber?.rawValue + nillableDictionary["outerEnum"] = self.outerEnum?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift index cf0d7c99512..2757afd722d 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -126,7 +126,8 @@ class Decoders { "yyyy-MM-dd'T'HH:mm:ssZZZZZ", "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'", - "yyyy-MM-dd'T'HH:mm:ss.SSS" + "yyyy-MM-dd'T'HH:mm:ss.SSS", + "yyyy-MM-dd HH:mm:ss" ].map { (format: String) -> DateFormatter in let formatter = DateFormatter() formatter.dateFormat = format @@ -141,7 +142,7 @@ class Decoders { } } } - if let sourceInt = source as? Int { + if let sourceInt = source as? Int64 { // treat as a java date return Date(timeIntervalSince1970: Double(sourceInt / 1000) ) } @@ -284,6 +285,20 @@ class Decoders { } + // Decoder for [ClassModel] + Decoders.addDecoder(clazz: [ClassModel].self) { (source: AnyObject) -> [ClassModel] in + return Decoders.decode(clazz: [ClassModel].self, source: source) + } + // Decoder for ClassModel + Decoders.addDecoder(clazz: ClassModel.self) { (source: AnyObject) -> ClassModel in + let sourceDictionary = source as! [AnyHashable: Any] + + let instance = ClassModel() + instance._class = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["_class"] as AnyObject?) + return instance + } + + // Decoder for [Client] Decoders.addDecoder(clazz: [Client].self) { (source: AnyObject) -> [Client] in return Decoders.decode(clazz: [Client].self, source: source) @@ -371,6 +386,7 @@ class Decoders { instance.enumNumber = EnumTest.EnumNumber(rawValue: (enumNumber)) } + instance.outerEnum = Decoders.decodeOptional(clazz: OuterEnum.self, source: sourceDictionary["outerEnum"] as AnyObject?) return instance } @@ -531,6 +547,21 @@ class Decoders { } + // Decoder for [OuterEnum] + Decoders.addDecoder(clazz: [OuterEnum].self) { (source: AnyObject) -> [OuterEnum] in + return Decoders.decode(clazz: [OuterEnum].self, source: source) + } + // Decoder for OuterEnum + Decoders.addDecoder(clazz: OuterEnum.self) { (source: AnyObject) -> OuterEnum in + if let source = source as? String { + if let result = OuterEnum(rawValue: source) { + return result + } + } + fatalError("Source \(source) is not convertible to enum type OuterEnum: Maybe swagger file is insufficient") + } + + // Decoder for [Pet] Decoders.addDecoder(clazz: [Pet].self) { (source: AnyObject) -> [Pet] in return Decoders.decode(clazz: [Pet].self, source: source) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index 03342500961..b3be1c99858 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -24,6 +24,7 @@ open class EnumTest: JSONEncodable { public var enumString: EnumString? public var enumInteger: EnumInteger? public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? public init() {} @@ -33,6 +34,7 @@ open class EnumTest: JSONEncodable { nillableDictionary["enum_string"] = self.enumString?.rawValue nillableDictionary["enum_integer"] = self.enumInteger?.rawValue nillableDictionary["enum_number"] = self.enumNumber?.rawValue + nillableDictionary["outerEnum"] = self.outerEnum?.encodeToJSON() let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } From f781f1df5b672a4da162dcd11c88d65abb6eb64b Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 7 Dec 2016 18:39:45 +0800 Subject: [PATCH 132/269] comment out xctool installation --- .travis.objc_swift_test.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.travis.objc_swift_test.yml b/.travis.objc_swift_test.yml index a9ffa3fd23e..e54776011fd 100644 --- a/.travis.objc_swift_test.yml +++ b/.travis.objc_swift_test.yml @@ -31,7 +31,8 @@ before_install: - gem install xcpretty -N --no-ri --no-rdoc - pod --version - pod setup --silent > /dev/null - - brew install xctool + # xctool already pre-installed + #- brew install xctool - git clone https://github.com/wing328/swagger-samples - cd swagger-samples/java/java-jersey-jaxrs && sudo mvn -q jetty:run & From 162352cb4b0c8bc05e5667cd5253d03fa57e6ab8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 7 Dec 2016 19:29:36 +0800 Subject: [PATCH 133/269] Fix maximum, minimum for `Integer` (#4335) * fix int/long max, min value (removing decimal) * fix integer min/max in parameter --- .../io/swagger/codegen/CodegenParameter.java | 4 +- .../io/swagger/codegen/CodegenProperty.java | 4 +- .../io/swagger/codegen/DefaultCodegen.java | 34 ++++++++++++++-- .../languages/FlaskConnexionCodegen.java | 8 ++-- .../ruby/lib/petstore/api/fake_api.rb | 16 ++++---- .../ruby/lib/petstore/api/store_api.rb | 8 ++-- .../ruby/lib/petstore/models/format_test.rb | 40 +++++++++---------- 7 files changed, 70 insertions(+), 44 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index c282fb519a2..75edc6b7fbd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -32,7 +32,7 @@ public class CodegenParameter { /** * See http://json-schema.org/latest/json-schema-validation.html#anchor17. */ - public Number maximum; + public String maximum; /** * See http://json-schema.org/latest/json-schema-validation.html#anchor17 */ @@ -40,7 +40,7 @@ public class CodegenParameter { /** * See http://json-schema.org/latest/json-schema-validation.html#anchor21 */ - public Number minimum; + public String minimum; /** * See http://json-schema.org/latest/json-schema-validation.html#anchor21 */ diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 66995f8d118..e4238b5cae6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -30,8 +30,8 @@ public class CodegenProperty implements Cloneable { public String example; public String jsonSchema; - public Double minimum; - public Double maximum; + public String minimum; + public String maximum; public Boolean exclusiveMinimum; public Boolean exclusiveMaximum; public Boolean hasMore, required, secondaryParam; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 265513d7189..5a4c69ff291 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1444,8 +1444,28 @@ public class DefaultCodegen { String type = getSwaggerType(p); if (p instanceof AbstractNumericProperty) { AbstractNumericProperty np = (AbstractNumericProperty) p; - property.minimum = np.getMinimum(); - property.maximum = np.getMaximum(); + if (np.getMinimum() != null) { + if (p instanceof BaseIntegerProperty) { // int, long + property.minimum = String.valueOf(np.getMinimum().longValue()); + } else { // double, decimal + property.minimum = String.valueOf(np.getMinimum()); + } + } else { + // set to null (empty) in mustache + property.minimum = null; + } + + if (np.getMaximum() != null) { + if (p instanceof BaseIntegerProperty) { // int, long + property.maximum = String.valueOf(np.getMaximum().longValue()); + } else { // double, decimal + property.maximum = String.valueOf(np.getMaximum()); + } + } else { + // set to null (empty) in mustache + property.maximum = null; + } + property.exclusiveMinimum = np.getExclusiveMinimum(); property.exclusiveMaximum = np.getExclusiveMaximum(); @@ -2314,9 +2334,15 @@ public class DefaultCodegen { } // validation - p.maximum = qp.getMaximum(); + // handle maximum, minimum properly for int/long by removing the trailing ".0" + if ("integer".equals(type)) { + p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue()); + p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue()); + } else { + p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum()); + p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum()); + } p.exclusiveMaximum = qp.isExclusiveMaximum(); - p.minimum = qp.getMinimum(); p.exclusiveMinimum = qp.isExclusiveMinimum(); p.maxLength = qp.getMaxLength(); p.minLength = qp.getMinLength(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 54bdb85c835..0f58aecc262 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -553,20 +553,20 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf example = "'" + escapeText(example) + "'"; } else if ("Integer".equals(type) || "int".equals(type)) { if(p.minimum != null) { - example = "" + (p.minimum.intValue() + 1); + example = "" + (Integer.valueOf(p.minimum) + 1); } if(p.maximum != null) { - example = "" + p.maximum.intValue(); + example = "" + p.maximum; } else if (example == null) { example = "56"; } } else if ("Long".equalsIgnoreCase(type)) { if(p.minimum != null) { - example = "" + (p.minimum.longValue() + 1); + example = "" + (Long.valueOf(p.minimum) + 1); } if(p.maximum != null) { - example = "" + p.maximum.longValue(); + example = "" + p.maximum; } else if (example == null) { example = "789"; } diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index c5cdf4da1c9..b869af1f445 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -145,20 +145,20 @@ module Petstore # verify the required parameter 'byte' is set fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" if byte.nil? - if !opts[:'integer'].nil? && opts[:'integer'] > 100.0 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.0.' + if !opts[:'integer'].nil? && opts[:'integer'] > 100 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.' end - if !opts[:'integer'].nil? && opts[:'integer'] < 10.0 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.0.' + if !opts[:'integer'].nil? && opts[:'integer'] < 10 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.' end - if !opts[:'int32'].nil? && opts[:'int32'] > 200.0 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.0.' + if !opts[:'int32'].nil? && opts[:'int32'] > 200 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.' end - if !opts[:'int32'].nil? && opts[:'int32'] < 20.0 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.0.' + if !opts[:'int32'].nil? && opts[:'int32'] < 20 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.' end if !opts[:'float'].nil? && opts[:'float'] > 987.6 diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 4f0e12c2ef0..78755496444 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -141,12 +141,12 @@ module Petstore end # verify the required parameter 'order_id' is set fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.get_order_by_id" if order_id.nil? - if order_id > 5.0 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.0.' + if order_id > 5 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.' end - if order_id < 1.0 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.0.' + if order_id < 1 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.' end # resource path diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index 2ed1ac73d6e..f77097d97a9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -145,20 +145,20 @@ module Petstore # @return Array for valid properies with the reasons def list_invalid_properties invalid_properties = Array.new - if !@integer.nil? && @integer > 100.0 - invalid_properties.push("invalid value for 'integer', must be smaller than or equal to 100.0.") + if !@integer.nil? && @integer > 100 + invalid_properties.push("invalid value for 'integer', must be smaller than or equal to 100.") end - if !@integer.nil? && @integer < 10.0 - invalid_properties.push("invalid value for 'integer', must be greater than or equal to 10.0.") + if !@integer.nil? && @integer < 10 + invalid_properties.push("invalid value for 'integer', must be greater than or equal to 10.") end - if !@int32.nil? && @int32 > 200.0 - invalid_properties.push("invalid value for 'int32', must be smaller than or equal to 200.0.") + if !@int32.nil? && @int32 > 200 + invalid_properties.push("invalid value for 'int32', must be smaller than or equal to 200.") end - if !@int32.nil? && @int32 < 20.0 - invalid_properties.push("invalid value for 'int32', must be greater than or equal to 20.0.") + if !@int32.nil? && @int32 < 20 + invalid_properties.push("invalid value for 'int32', must be greater than or equal to 20.") end if @number.nil? @@ -219,10 +219,10 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - return false if !@integer.nil? && @integer > 100.0 - return false if !@integer.nil? && @integer < 10.0 - return false if !@int32.nil? && @int32 > 200.0 - return false if !@int32.nil? && @int32 < 20.0 + return false if !@integer.nil? && @integer > 100 + return false if !@integer.nil? && @integer < 10 + return false if !@int32.nil? && @int32 > 200 + return false if !@int32.nil? && @int32 < 20 return false if @number.nil? return false if @number > 543.2 return false if @number < 32.1 @@ -243,12 +243,12 @@ module Petstore # @param [Object] integer Value to be assigned def integer=(integer) - if !integer.nil? && integer > 100.0 - fail ArgumentError, "invalid value for 'integer', must be smaller than or equal to 100.0." + if !integer.nil? && integer > 100 + fail ArgumentError, "invalid value for 'integer', must be smaller than or equal to 100." end - if !integer.nil? && integer < 10.0 - fail ArgumentError, "invalid value for 'integer', must be greater than or equal to 10.0." + if !integer.nil? && integer < 10 + fail ArgumentError, "invalid value for 'integer', must be greater than or equal to 10." end @integer = integer @@ -258,12 +258,12 @@ module Petstore # @param [Object] int32 Value to be assigned def int32=(int32) - if !int32.nil? && int32 > 200.0 - fail ArgumentError, "invalid value for 'int32', must be smaller than or equal to 200.0." + if !int32.nil? && int32 > 200 + fail ArgumentError, "invalid value for 'int32', must be smaller than or equal to 200." end - if !int32.nil? && int32 < 20.0 - fail ArgumentError, "invalid value for 'int32', must be greater than or equal to 20.0." + if !int32.nil? && int32 < 20 + fail ArgumentError, "invalid value for 'int32', must be greater than or equal to 20." end @int32 = int32 From 56d5b54599c44468aa50eb448498e4cbe7843f9b Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 7 Dec 2016 23:23:40 +0800 Subject: [PATCH 134/269] add tests for swift3 client in travis objc/swift config --- .travis.objc_swift_test.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.objc_swift_test.yml b/.travis.objc_swift_test.yml index e54776011fd..8f7cf3b922d 100644 --- a/.travis.objc_swift_test.yml +++ b/.travis.objc_swift_test.yml @@ -48,6 +48,10 @@ script: - cd $SW/samples/client/petstore/swift/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty # test default swift client - cd $SW/samples/client/petstore/swift/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty + # test swift3 client with promisekit + - cd $SW/samples/client/petstore/swift3/promisekit/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty + # test default swift3 client + - cd $SW/samples/client/petstore/swift3/default/SwaggerClientTests && pod install && xcodebuild clean test -workspace "SwaggerClient.xcworkspace" -scheme "SwaggerClient" -sdk iphonesimulator GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=YES GCC_GENERATE_TEST_COVERAGE_FILES=YES | xcpretty env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From a2c2a77a933dc9cd223b6c5bc0a88a632605eb91 Mon Sep 17 00:00:00 2001 From: Sergey Kondratov Date: Thu, 8 Dec 2016 09:22:01 +0700 Subject: [PATCH 135/269] Added Saritasa to list of Companies (#4343) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index a2b40c7f8ff..7e3cd797b9b 100644 --- a/README.md +++ b/README.md @@ -807,6 +807,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Revault Sàrl](http://revault.ch) - [Riffyn](https://riffyn.com) - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) +- [Saritasa](https://www.saritasa.com/) - [SCOOP Software GmbH](http://www.scoop-software.de) - [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) From 939a8052f3bb0d5180c4d64f5e5c015f4c2c516f Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Dec 2016 15:22:55 +0800 Subject: [PATCH 136/269] [Java] Uncomment @Max @Min syntax in bean validation files (#4340) * uncomment max min syntax in bean validation files (java) * remove eol at the end of the file --- .../src/main/resources/Java/beanValidation.mustache | 4 ++-- .../src/main/resources/JavaJaxRS/cxf/beanValidation.mustache | 4 ++-- .../JavaJaxRS/cxf/beanValidationQueryParams.mustache | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache index 1cd5d386106..f13ed596859 100644 --- a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -35,8 +35,8 @@ {{/maxItems}} {{/minItems}} {{#minimum}} - //@Min({{minimum}}) + @Min({{minimum}}) {{/minimum}} {{#maximum}} - //@Max({{maximum}}) + @Max({{maximum}}) {{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache index 1cd5d386106..f13ed596859 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache @@ -35,8 +35,8 @@ {{/maxItems}} {{/minItems}} {{#minimum}} - //@Min({{minimum}}) + @Min({{minimum}}) {{/minimum}} {{#maximum}} - //@Max({{maximum}}) + @Max({{maximum}}) {{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache index cca08f4b2c4..52440b12218 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidationQueryParams.mustache @@ -1 +1 @@ -{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}}/* @Min({{minimum}}) */{{/minimum}}{{#maximum}}/* @Max({{maximum}}) */{{/maximum}} \ No newline at end of file +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file From a0c4b58b53227ff22f162d60a54b30b10f8f71a2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Dec 2016 15:59:06 +0800 Subject: [PATCH 137/269] add guid mapping for c# 2.0 (#4347) --- .../swagger/codegen/languages/CsharpDotNet2ClientCodegen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 0750a667b3a..9537b7abc2c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -65,6 +65,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege "Integer", "Long", "Float", + "Guid?", "System.IO.Stream", // not really a primitive, we include it to avoid model import "Object") ); @@ -86,6 +87,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege typeMapping.put("list", "List"); typeMapping.put("map", "Dictionary"); typeMapping.put("object", "Object"); + typeMapping.put("uuid", "Guid?"); cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name (convention: Camel.Case).") From a3d30821059e882f6434b0ff1f0ab07475f4f6e3 Mon Sep 17 00:00:00 2001 From: Christopher Chiche Date: Thu, 8 Dec 2016 09:01:50 +0100 Subject: [PATCH 138/269] [Typescript/Fetch] Fix tslint issues in generated code (#4313) * [Typescript/Fetch] Fix tslint issues in generated code * Add security generated files. * Use tslint version that doesn't require typescript 2 * Run build scripts --- .../TypeScriptFetchClientCodegen.java | 1 + .../resources/TypeScript-Fetch/api.mustache | 12 ++- .../TypeScript-Fetch/package.json.mustache | 4 +- .../TypeScript-Fetch/tslint.json.mustache | 101 ++++++++++++++++++ .../typescript-fetch/api.ts | 30 ++---- .../typescript-fetch/package.json | 6 +- .../typescript-fetch/tslint.json | 101 ++++++++++++++++++ .../typescript-fetch/builds/default/api.ts | 10 +- .../builds/default/package.json | 4 +- .../builds/default/tslint.json | 101 ++++++++++++++++++ .../typescript-fetch/builds/es6-target/api.ts | 10 +- .../builds/es6-target/package.json | 4 +- .../builds/es6-target/tslint.json | 101 ++++++++++++++++++ .../builds/with-npm-version/api.ts | 10 +- .../builds/with-npm-version/package.json | 4 +- .../builds/with-npm-version/tslint.json | 101 ++++++++++++++++++ 16 files changed, 553 insertions(+), 47 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tslint.json.mustache create mode 100644 samples/client/petstore-security-test/typescript-fetch/tslint.json create mode 100644 samples/client/petstore/typescript-fetch/builds/default/tslint.json create mode 100644 samples/client/petstore/typescript-fetch/builds/es6-target/tslint.json create mode 100644 samples/client/petstore/typescript-fetch/builds/with-npm-version/tslint.json diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index edde98f3e8d..a6449587ac3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -40,6 +40,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); + supportingFiles.add(new SupportingFile("tslint.json.mustache", "", "tslint.json")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); if(additionalProperties.containsKey(NPM_NAME)) { diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index b3cfa638030..907089e33bd 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -10,7 +10,7 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ''); +const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ""); export interface FetchArgs { url: string; @@ -83,8 +83,10 @@ export const {{classname}}FetchParamCreactor = { .replace(`{${"{{baseName}}"}}`, `${ params["{{paramName}}"] }`){{/pathParams}}; let urlObj = url.parse(baseUrl, true); {{#hasQueryParams}} - urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { {{#queryParams}} - "{{baseName}}": params["{{paramName}}"],{{/queryParams}} + urlObj.query = {{#supportsES6}}Object.{{/supportsES6}}assign({}, urlObj.query, { + {{#queryParams}} + "{{baseName}}": params["{{paramName}}"], + {{/queryParams}} }); {{/hasQueryParams}} let fetchOptions: RequestInit = {{#supportsES6}}Object.{{/supportsES6}}assign({}, { method: "{{httpMethod}}" }, options); @@ -103,8 +105,8 @@ export const {{classname}}FetchParamCreactor = { }{{/bodyParam}} {{/hasBodyParam}} {{#hasHeaderParams}} - fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ {{#headerParams}} - "{{baseName}}": params["{{paramName}}"],{{/headerParams}} + fetchOptions.headers = {{#supportsES6}}Object.{{/supportsES6}}assign({ + {{#headerParams}}"{{baseName}}": params["{{paramName}}"],{{/headerParams}} }, contentTypeHeader); {{/hasHeaderParams}} {{^hasHeaderParams}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache index 5243c579c29..05aec69d7ec 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -10,9 +10,11 @@ {{/supportsES6}}"isomorphic-fetch": "^2.2.1" }, "scripts" : { - "prepublish" : "typings install && tsc" + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" }, "devDependencies": { + "tslint": "^3.15.1", "typescript": "^1.8.10", "typings": "^1.0.4" } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tslint.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tslint.json.mustache new file mode 100644 index 00000000000..6eb02acec8c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tslint.json.mustache @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/samples/client/petstore-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts index e935898c22f..6936a0ffb53 100644 --- a/samples/client/petstore-security-test/typescript-fetch/api.ts +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -8,18 +8,6 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ import * as querystring from "querystring"; @@ -31,7 +19,7 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r".replace(/\/+$/, ''); +const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r".replace(/\/+$/, ""); export interface FetchArgs { url: string; @@ -46,7 +34,7 @@ export class BaseAPI { this.basePath = basePath; this.fetch = fetch; } -} +}; /** * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r @@ -68,7 +56,7 @@ export const FakeApiFetchParamCreactor = { * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any): FetchArgs { + testCodeInjectEndRnNR(params: { "test code inject * ' " =end rn n r"?: string; }, options?: any): FetchArgs { const baseUrl = `/fake`; let urlObj = url.parse(baseUrl, true); let fetchOptions: RequestInit = assign({}, { method: "PUT" }, options); @@ -76,7 +64,7 @@ export const FakeApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ - "test code inject */ ' " =end -- \r\n \n \r": params.test code inject * ' " =end rn n r, + "test code inject */ ' " =end -- \r\n \n \r": params["test code inject * ' " =end rn n r"], }); if (contentTypeHeader) { fetchOptions.headers = contentTypeHeader; @@ -86,7 +74,7 @@ export const FakeApiFetchParamCreactor = { options: fetchOptions, }; }, -} +}; /** * FakeApi - functional programming interface @@ -96,7 +84,7 @@ export const FakeApiFp = { * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { + testCodeInjectEndRnNR(params: { "test code inject * ' " =end rn n r"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { @@ -118,7 +106,7 @@ export class FakeApi extends BaseAPI { * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any) { + testCodeInjectEndRnNR(params: { "test code inject * ' " =end rn n r"?: string; }, options?: any) { return FakeApiFp.testCodeInjectEndRnNR(params, options)(this.fetch, this.basePath); } }; @@ -132,9 +120,9 @@ export const FakeApiFactory = function (fetch?: FetchAPI, basePath?: string) { * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r */ - testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }, options?: any) { + testCodeInjectEndRnNR(params: { "test code inject * ' " =end rn n r"?: string; }, options?: any) { return FakeApiFp.testCodeInjectEndRnNR(params, options)(fetch, basePath); }, - } + }; }; diff --git a/samples/client/petstore-security-test/typescript-fetch/package.json b/samples/client/petstore-security-test/typescript-fetch/package.json index 97e572353a3..0204e3c39c9 100644 --- a/samples/client/petstore-security-test/typescript-fetch/package.json +++ b/samples/client/petstore-security-test/typescript-fetch/package.json @@ -1,7 +1,7 @@ { "name": "typescript-fetch-api", "version": "0.0.0", - "license": "Apache-2.0", + "license": "Unlicense", "main": "./dist/api.js", "browser": "./dist/api.js", "typings": "./dist/api.d.ts", @@ -10,9 +10,11 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "prepublish" : "typings install && tsc" + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" }, "devDependencies": { + "tslint": "^3.15.1", "typescript": "^1.8.10", "typings": "^1.0.4" } diff --git a/samples/client/petstore-security-test/typescript-fetch/tslint.json b/samples/client/petstore-security-test/typescript-fetch/tslint.json new file mode 100644 index 00000000000..6eb02acec8c --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/tslint.json @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index fdf7cbc5cdc..c8445d1edfb 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -19,7 +19,7 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); +const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); export interface FetchArgs { url: string; @@ -132,7 +132,7 @@ export const PetApiFetchParamCreactor = { let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; - fetchOptions.headers = assign({ + fetchOptions.headers = assign({ "api_key": params["apiKey"], }, contentTypeHeader); return { @@ -148,7 +148,7 @@ export const PetApiFetchParamCreactor = { findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "status": params["status"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -170,7 +170,7 @@ export const PetApiFetchParamCreactor = { findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "tags": params["tags"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -970,7 +970,7 @@ export const UserApiFetchParamCreactor = { loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "username": params["username"], "password": params["password"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/default/package.json b/samples/client/petstore/typescript-fetch/builds/default/package.json index ce62ea19fbe..0204e3c39c9 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/package.json +++ b/samples/client/petstore/typescript-fetch/builds/default/package.json @@ -10,9 +10,11 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "prepublish" : "typings install && tsc" + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" }, "devDependencies": { + "tslint": "^3.15.1", "typescript": "^1.8.10", "typings": "^1.0.4" } diff --git a/samples/client/petstore/typescript-fetch/builds/default/tslint.json b/samples/client/petstore/typescript-fetch/builds/default/tslint.json new file mode 100644 index 00000000000..6eb02acec8c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/default/tslint.json @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 2a5a95b3c21..832e5417e0e 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -18,7 +18,7 @@ import * as isomorphicFetch from "isomorphic-fetch"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); +const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); export interface FetchArgs { url: string; @@ -131,7 +131,7 @@ export const PetApiFetchParamCreactor = { let fetchOptions: RequestInit = Object.assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; - fetchOptions.headers = Object.assign({ + fetchOptions.headers = Object.assign({ "api_key": params["apiKey"], }, contentTypeHeader); return { @@ -147,7 +147,7 @@ export const PetApiFetchParamCreactor = { findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); - urlObj.query = Object.assign({}, urlObj.query, { + urlObj.query = Object.assign({}, urlObj.query, { "status": params["status"], }); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -169,7 +169,7 @@ export const PetApiFetchParamCreactor = { findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); - urlObj.query = Object.assign({}, urlObj.query, { + urlObj.query = Object.assign({}, urlObj.query, { "tags": params["tags"], }); let fetchOptions: RequestInit = Object.assign({}, { method: "GET" }, options); @@ -969,7 +969,7 @@ export const UserApiFetchParamCreactor = { loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); - urlObj.query = Object.assign({}, urlObj.query, { + urlObj.query = Object.assign({}, urlObj.query, { "username": params["username"], "password": params["password"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/package.json b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json index e05dd91ca8c..9797e3483f9 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/package.json +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/package.json @@ -9,9 +9,11 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "prepublish" : "typings install && tsc" + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" }, "devDependencies": { + "tslint": "^3.15.1", "typescript": "^1.8.10", "typings": "^1.0.4" } diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/tslint.json b/samples/client/petstore/typescript-fetch/builds/es6-target/tslint.json new file mode 100644 index 00000000000..6eb02acec8c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/tslint.json @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index fdf7cbc5cdc..c8445d1edfb 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -19,7 +19,7 @@ import * as assign from "core-js/library/fn/object/assign"; interface Dictionary { [index: string]: T; } export interface FetchAPI { (url: string, init?: any): Promise; } -const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ''); +const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); export interface FetchArgs { url: string; @@ -132,7 +132,7 @@ export const PetApiFetchParamCreactor = { let fetchOptions: RequestInit = assign({}, { method: "DELETE" }, options); let contentTypeHeader: Dictionary; - fetchOptions.headers = assign({ + fetchOptions.headers = assign({ "api_key": params["apiKey"], }, contentTypeHeader); return { @@ -148,7 +148,7 @@ export const PetApiFetchParamCreactor = { findPetsByStatus(params: { "status"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByStatus`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "status": params["status"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -170,7 +170,7 @@ export const PetApiFetchParamCreactor = { findPetsByTags(params: { "tags"?: Array; }, options?: any): FetchArgs { const baseUrl = `/pet/findByTags`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "tags": params["tags"], }); let fetchOptions: RequestInit = assign({}, { method: "GET" }, options); @@ -970,7 +970,7 @@ export const UserApiFetchParamCreactor = { loginUser(params: { "username"?: string; "password"?: string; }, options?: any): FetchArgs { const baseUrl = `/user/login`; let urlObj = url.parse(baseUrl, true); - urlObj.query = assign({}, urlObj.query, { + urlObj.query = assign({}, urlObj.query, { "username": params["username"], "password": params["password"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json index 07cbcf57454..f4c8ca8a162 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/package.json @@ -10,9 +10,11 @@ "isomorphic-fetch": "^2.2.1" }, "scripts" : { - "prepublish" : "typings install && tsc" + "prepublish" : "typings install && tsc", + "test": "tslint api.ts" }, "devDependencies": { + "tslint": "^3.15.1", "typescript": "^1.8.10", "typings": "^1.0.4" } diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/tslint.json b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tslint.json new file mode 100644 index 00000000000..6eb02acec8c --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/tslint.json @@ -0,0 +1,101 @@ +{ + "jsRules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-duplicate-variable": true, + "no-eval": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + }, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces" + ], + "no-eval": true, + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-unsafe-finally": true, + "no-var-keyword": true, + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "quotemark": [ + true, + "double" + ], + "semicolon": [ + true, + "always" + ], + "triple-equals": [ + true, + "allow-null-check" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + } + ], + "variable-name": [ + true, + "ban-keywords" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-separator", + "check-type" + ] + } +} From 535b233ff78127e38a585cb18e9e8f89e70aef03 Mon Sep 17 00:00:00 2001 From: Josh Williams Date: Thu, 8 Dec 2016 02:14:25 -0600 Subject: [PATCH 139/269] Fix for #4344 - update compile.mustache with new dependencies (#4345) * Fix for #4344 - update compile.mustache with new dependencies * Fix compile.mustache to use generatePropertyChanged flag for DLLs --- .../src/main/resources/csharp/compile.mustache | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache index 597e10c1e91..8d9f9bf344e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache @@ -17,5 +17,10 @@ if not exist ".\bin" mkdir bin copy packages\Newtonsoft.Json.8.0.3\lib\{{targetFrameworkNuget}}\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\{{targetFrameworkNuget}}\RestSharp.dll bin\RestSharp.dll +{{#generatePropertyChanged}} +copy packages\Fody.1.29.2\Fody.dll bin\Fody.dll +copy packages\PropertyChanged.Fody.1.51.3\PropertyChanged.Fody.dll bin\PropertyChanged.Fody.dll +copy packages\PropertyChanged.Fody.1.51.3\Lib\dotnet\PropertyChanged.dll bin\PropertyChanged.dll +{{/generatePropertyChanged}} +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.dll {{#generatePropertyChanged}}/r:bin\Fody.dll;bin\PropertyChanged.Fody.dll;bin\PropertyChanged.dll{{/generatePropertyChanged}} /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml -%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\{{packageName}}.dll /recurse:src\{{packageName}}\*.cs /doc:bin\{{packageName}}.xml From af2db27a8389f98d61960e58c710d98452f003e2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Dec 2016 18:09:20 +0800 Subject: [PATCH 140/269] remove trailing space in ts fetech api, add npm test to ci (#4348) --- .../main/resources/TypeScript-Fetch/api.mustache | 6 ++++-- .../petstore/typescript-fetch/builds/default/api.ts | 4 ++-- .../typescript-fetch/builds/default/pom.xml | 13 +++++++++++++ .../typescript-fetch/builds/es6-target/api.ts | 4 ++-- .../typescript-fetch/builds/es6-target/pom.xml | 13 +++++++++++++ .../typescript-fetch/builds/with-npm-version/api.ts | 4 ++-- .../builds/with-npm-version/pom.xml | 13 +++++++++++++ 7 files changed, 49 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 907089e33bd..16a41ff983b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -94,8 +94,10 @@ export const {{classname}}FetchParamCreactor = { let contentTypeHeader: Dictionary; {{#hasFormParams}} contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ {{#formParams}} - "{{baseName}}": params["{{paramName}}"],{{/formParams}} + fetchOptions.body = querystring.stringify({ + {{#formParams}} + "{{baseName}}": params["{{paramName}}"], + {{/formParams}} }); {{/hasFormParams}} {{#hasBodyParam}} diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index c8445d1edfb..917785c47da 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -250,7 +250,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "name": params["name"], "status": params["status"], }); @@ -281,7 +281,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "additionalMetadata": params["additionalMetadata"], "file": params["file"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/default/pom.xml b/samples/client/petstore/typescript-fetch/builds/default/pom.xml index 53722c49e7b..f7886b3f9aa 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/pom.xml +++ b/samples/client/petstore/typescript-fetch/builds/default/pom.xml @@ -39,6 +39,19 @@ + + npm-test + integration-test + + exec + + + npm + + test + + + diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 832e5417e0e..7bbbe76ca50 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -249,7 +249,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "name": params["name"], "status": params["status"], }); @@ -280,7 +280,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "additionalMetadata": params["additionalMetadata"], "file": params["file"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml b/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml index 8730e7c4377..8b8e6052761 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/pom.xml @@ -39,6 +39,19 @@ + + npm-test + integration-test + + exec + + + npm + + test + + + diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index c8445d1edfb..917785c47da 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -250,7 +250,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "name": params["name"], "status": params["status"], }); @@ -281,7 +281,7 @@ export const PetApiFetchParamCreactor = { let contentTypeHeader: Dictionary; contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; - fetchOptions.body = querystring.stringify({ + fetchOptions.body = querystring.stringify({ "additionalMetadata": params["additionalMetadata"], "file": params["file"], }); diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml b/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml index 4a4380291ca..210ee3c10a1 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/pom.xml @@ -39,6 +39,19 @@ + + npm-test + integration-test + + exec + + + npm + + test + + + From 9051848ffa5435b80d37afeb7070a07fa495c9c9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Dec 2016 23:24:20 +0800 Subject: [PATCH 141/269] minor fix to petstore test spec --- .../2_0/petstore-with-fake-endpoints-models-for-testing.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index c7782a53be7..5809cb33122 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -565,7 +565,7 @@ paths: tags: - fake summary: To test "client" model - descriptions: To test "client" model + description: To test "client" model operationId: testClientModel consumes: - application/json @@ -587,7 +587,7 @@ paths: tags: - fake summary: To test enum parameters - descriptions: To test enum parameters + description: To test enum parameters operationId: testEnumParameters consumes: - "*/*" @@ -1080,7 +1080,6 @@ definitions: - 1.1 - -1.2 outerEnum: - type: string $ref: '#/definitions/OuterEnum' AdditionalPropertiesClass: type: object From a0f2b235f162e0685a4b4e3402dab71aa0cab0d3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Dec 2016 00:03:38 +0800 Subject: [PATCH 142/269] [C#] fix build.sh for PropertyChanged feature in C# API client (#4349) * fix build.sh for PropertyChange in C# * add new csharp files * manual fix to enum ref in c# client --- .../resources/csharp/compile-mono.sh.mustache | 10 ++ .../csharp/SwaggerClient/IO.Swagger.sln | 10 +- .../petstore/csharp/SwaggerClient/README.md | 2 + .../petstore/csharp/SwaggerClient/build.bat | 2 +- .../csharp/SwaggerClient/docs/ClassModel.md | 9 ++ .../csharp/SwaggerClient/docs/EnumTest.md | 1 + .../csharp/SwaggerClient/docs/FakeApi.md | 6 +- .../csharp/SwaggerClient/docs/OuterEnum.md | 8 + .../Model/ArrayOfArrayOfNumberOnlyTests.cs | 78 ++++++++++ .../Model/ArrayOfNumberOnlyTests.cs | 78 ++++++++++ .../IO.Swagger.Test/Model/ClassModelTests.cs | 78 ++++++++++ .../IO.Swagger.Test/Model/EnumArraysTests.cs | 86 +++++++++++ .../Model/HasOnlyReadOnlyTests.cs | 86 +++++++++++ .../src/IO.Swagger.Test/Model/ListTests.cs | 78 ++++++++++ .../src/IO.Swagger.Test/Model/MapTestTests.cs | 86 +++++++++++ .../IO.Swagger.Test/Model/ModelClientTests.cs | 78 ++++++++++ .../IO.Swagger.Test/Model/NumberOnlyTests.cs | 78 ++++++++++ .../IO.Swagger.Test/Model/OuterEnumTests.cs | 70 +++++++++ .../src/IO.Swagger/Api/FakeApi.cs | 16 +- .../src/IO.Swagger/IO.Swagger.csproj | 3 +- .../src/IO.Swagger/Model/ClassModel.cs | 121 ++++++++++++++++ .../src/IO.Swagger/Model/EnumTest.cs | 17 ++- .../src/IO.Swagger/Model/FormatTest.cs | 16 +- .../src/IO.Swagger/Model/OuterEnum.cs | 52 +++++++ .../.travis.yml | 12 -- .../IO.Swagger.sln | 10 +- .../README.md | 12 +- .../build.bat | 17 +-- .../SwaggerClientWithPropertyChanged/build.sh | 17 +-- .../docs/ClassModel.md | 9 ++ .../docs/EnumTest.md | 1 + .../docs/FakeApi.md | 16 +- .../docs/OuterEnum.md | 8 + .../mono_nunit_test.sh | 11 -- .../IO.Swagger.Test/IO.Swagger.Test.csproj | 15 +- .../IO.Swagger.Test/Model/ClassModelTests.cs | 78 ++++++++++ .../IO.Swagger.Test/Model/OuterEnumTests.cs | 70 +++++++++ .../src/IO.Swagger/Api/FakeApi.cs | 66 ++++----- .../src/IO.Swagger/Api/PetApi.cs | 12 -- .../src/IO.Swagger/Api/StoreApi.cs | 12 -- .../src/IO.Swagger/Api/UserApi.cs | 12 -- .../src/IO.Swagger/Client/ApiClient.cs | 12 -- .../src/IO.Swagger/Client/ApiException.cs | 12 -- .../src/IO.Swagger/Client/ApiResponse.cs | 12 -- .../src/IO.Swagger/Client/Configuration.cs | 12 -- .../src/IO.Swagger/Client/ExceptionFactory.cs | 12 -- .../src/IO.Swagger/Client/IApiAccessor.cs | 12 -- .../src/IO.Swagger/IO.Swagger.csproj | 15 +- .../Model/AdditionalPropertiesClass.cs | 12 -- .../src/IO.Swagger/Model/Animal.cs | 12 -- .../src/IO.Swagger/Model/AnimalFarm.cs | 12 -- .../src/IO.Swagger/Model/ApiResponse.cs | 12 -- .../Model/ArrayOfArrayOfNumberOnly.cs | 12 -- .../src/IO.Swagger/Model/ArrayOfNumberOnly.cs | 12 -- .../src/IO.Swagger/Model/ArrayTest.cs | 12 -- .../src/IO.Swagger/Model/Cat.cs | 12 -- .../src/IO.Swagger/Model/Category.cs | 12 -- .../src/IO.Swagger/Model/ClassModel.cs | 137 ++++++++++++++++++ .../src/IO.Swagger/Model/Dog.cs | 12 -- .../src/IO.Swagger/Model/EnumArrays.cs | 12 -- .../src/IO.Swagger/Model/EnumClass.cs | 12 -- .../src/IO.Swagger/Model/EnumTest.cs | 29 ++-- .../src/IO.Swagger/Model/FormatTest.cs | 28 +--- .../src/IO.Swagger/Model/HasOnlyReadOnly.cs | 12 -- .../src/IO.Swagger/Model/List.cs | 12 -- .../src/IO.Swagger/Model/MapTest.cs | 12 -- ...dPropertiesAndAdditionalPropertiesClass.cs | 12 -- .../src/IO.Swagger/Model/Model200Response.cs | 12 -- .../src/IO.Swagger/Model/ModelClient.cs | 12 -- .../src/IO.Swagger/Model/ModelReturn.cs | 12 -- .../src/IO.Swagger/Model/Name.cs | 12 -- .../src/IO.Swagger/Model/NumberOnly.cs | 12 -- .../src/IO.Swagger/Model/Order.cs | 12 -- .../src/IO.Swagger/Model/OuterEnum.cs | 54 +++++++ .../src/IO.Swagger/Model/Pet.cs | 12 -- .../src/IO.Swagger/Model/ReadOnlyFirst.cs | 12 -- .../src/IO.Swagger/Model/SpecialModelName.cs | 12 -- .../src/IO.Swagger/Model/Tag.cs | 12 -- .../src/IO.Swagger/Model/User.cs | 12 -- 79 files changed, 1489 insertions(+), 617 deletions(-) create mode 100644 samples/client/petstore/csharp/SwaggerClient/docs/ClassModel.md create mode 100644 samples/client/petstore/csharp/SwaggerClient/docs/OuterEnum.md create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ClassModelTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumArraysTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelClientTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NumberOnlyTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OuterEnumTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs create mode 100644 samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/OuterEnum.cs create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ClassModel.md create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/OuterEnum.md create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ClassModelTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OuterEnumTests.cs create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs create mode 100644 samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/OuterEnum.cs diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache index 792b1f50b5e..52d2fb767f8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -17,9 +17,19 @@ echo "[INFO] Copy DLLs to the 'bin' folder" mkdir -p bin; cp packages/Newtonsoft.Json.8.0.3/lib/{{targetFrameworkNuget}}/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/{{targetFrameworkNuget}}/RestSharp.dll bin/RestSharp.dll; +{{#generatePropertyChanged}} +cp packages/Fody.1.29.2/Fody.dll bin/Fody.dll +cp packages/PropertyChanged.Fody.1.51.3/PropertyChanged.Fody.dll bin/PropertyChanged.Fody.dll +cp packages/PropertyChanged.Fody.1.51.3/Lib/dotnet/PropertyChanged.dll bin/PropertyChanged.dll +{{/generatePropertyChanged}} echo "[INFO] Run 'mcs' to build bin/{{{packageName}}}.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ +{{#generatePropertyChanged}} +bin/Fody.dll,\ +bin/PropertyChanged.Fody.dll,\ +bin/PropertyChanged.dll,\ +{{/generatePropertyChanged}} bin/RestSharp.dll,\ System.ComponentModel.DataAnnotations.dll,\ System.Runtime.Serialization.dll \ diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index aec07274033..0b538e4e73f 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{CD650877-711F-40DC-9804-E09CE6CF93CE}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{CD650877-711F-40DC-9804-E09CE6CF93CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{CD650877-711F-40DC-9804-E09CE6CF93CE}.Debug|Any CPU.Build.0 = Debug|Any CPU -{CD650877-711F-40DC-9804-E09CE6CF93CE}.Release|Any CPU.ActiveCfg = Release|Any CPU -{CD650877-711F-40DC-9804-E09CE6CF93CE}.Release|Any CPU.Build.0 = Release|Any CPU +{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Debug|Any CPU.Build.0 = Debug|Any CPU +{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Release|Any CPU.ActiveCfg = Release|Any CPU +{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 28bc846a21c..67a001aa0cf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -117,6 +117,7 @@ Class | Method | HTTP request | Description - [Model.ArrayTest](docs/ArrayTest.md) - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) + - [Model.ClassModel](docs/ClassModel.md) - [Model.Dog](docs/Dog.md) - [Model.EnumArrays](docs/EnumArrays.md) - [Model.EnumClass](docs/EnumClass.md) @@ -132,6 +133,7 @@ Class | Method | HTTP request | Description - [Model.Name](docs/Name.md) - [Model.NumberOnly](docs/NumberOnly.md) - [Model.Order](docs/Order.md) + - [Model.OuterEnum](docs/OuterEnum.md) - [Model.Pet](docs/Pet.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Model.SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/build.bat b/samples/client/petstore/csharp/SwaggerClient/build.bat index 10b64bc1307..1da4812b36b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/build.bat +++ b/samples/client/petstore/csharp/SwaggerClient/build.bat @@ -12,5 +12,5 @@ if not exist ".\bin" mkdir bin copy packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml -%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/ClassModel.md b/samples/client/petstore/csharp/SwaggerClient/docs/ClassModel.md new file mode 100644 index 00000000000..760130f053c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/ClassModel.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ClassModel +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md b/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md index f0f300021b5..a4371a96695 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **EnumString** | **string** | | [optional] **EnumInteger** | **int?** | | [optional] **EnumNumber** | **double?** | | [optional] +**OuterEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index e6d8b043475..8dd5de759ee 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -162,7 +162,7 @@ void (empty response body) # **TestEnumParameters** -> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) +> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) To test enum parameters @@ -188,7 +188,7 @@ namespace Example var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) var enumQueryString = enumQueryString_example; // string | Query parameter enum test (string) (optional) (default to -efg) - var enumQueryInteger = 3.4; // decimal? | Query parameter enum test (double) (optional) + var enumQueryInteger = 56; // int? | Query parameter enum test (double) (optional) var enumQueryDouble = 1.2; // double? | Query parameter enum test (double) (optional) try @@ -215,7 +215,7 @@ Name | Type | Description | Notes **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] - **enumQueryInteger** | **decimal?**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **int?**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/OuterEnum.md b/samples/client/petstore/csharp/SwaggerClient/docs/OuterEnum.md new file mode 100644 index 00000000000..55eb118a349 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/OuterEnum.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterEnum +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..048173f80ef --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfArrayOfNumberOnlyTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ArrayOfArrayOfNumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayOfArrayOfNumberOnlyTests + { + // TODO uncomment below to declare an instance variable for ArrayOfArrayOfNumberOnly + //private ArrayOfArrayOfNumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ArrayOfArrayOfNumberOnly + //instance = new ArrayOfArrayOfNumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayOfArrayOfNumberOnly + /// + [Test] + public void ArrayOfArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ArrayOfArrayOfNumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfArrayOfNumberOnly"); + } + + /// + /// Test the property 'ArrayArrayNumber' + /// + [Test] + public void ArrayArrayNumberTest() + { + // TODO unit test for the property 'ArrayArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs new file mode 100644 index 00000000000..fafa4caf843 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ArrayOfNumberOnlyTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ArrayOfNumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ArrayOfNumberOnlyTests + { + // TODO uncomment below to declare an instance variable for ArrayOfNumberOnly + //private ArrayOfNumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ArrayOfNumberOnly + //instance = new ArrayOfNumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ArrayOfNumberOnly + /// + [Test] + public void ArrayOfNumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ArrayOfNumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ArrayOfNumberOnly"); + } + + /// + /// Test the property 'ArrayNumber' + /// + [Test] + public void ArrayNumberTest() + { + // TODO unit test for the property 'ArrayNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ClassModelTests.cs new file mode 100644 index 00000000000..01b2c5b9c1b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ClassModelTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ClassModelTests + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ClassModel + /// + [Test] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ClassModel + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ClassModel"); + } + + /// + /// Test the property '_Class' + /// + [Test] + public void _ClassTest() + { + // TODO unit test for the property '_Class' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumArraysTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumArraysTests.cs new file mode 100644 index 00000000000..eb76effacc7 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/EnumArraysTests.cs @@ -0,0 +1,86 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing EnumArrays + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class EnumArraysTests + { + // TODO uncomment below to declare an instance variable for EnumArrays + //private EnumArrays instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of EnumArrays + //instance = new EnumArrays(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of EnumArrays + /// + [Test] + public void EnumArraysInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" EnumArrays + //Assert.IsInstanceOfType (instance, "variable 'instance' is a EnumArrays"); + } + + /// + /// Test the property 'JustSymbol' + /// + [Test] + public void JustSymbolTest() + { + // TODO unit test for the property 'JustSymbol' + } + /// + /// Test the property 'ArrayEnum' + /// + [Test] + public void ArrayEnumTest() + { + // TODO unit test for the property 'ArrayEnum' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs new file mode 100644 index 00000000000..d2be5717c4e --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/HasOnlyReadOnlyTests.cs @@ -0,0 +1,86 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing HasOnlyReadOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class HasOnlyReadOnlyTests + { + // TODO uncomment below to declare an instance variable for HasOnlyReadOnly + //private HasOnlyReadOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of HasOnlyReadOnly + //instance = new HasOnlyReadOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of HasOnlyReadOnly + /// + [Test] + public void HasOnlyReadOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" HasOnlyReadOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a HasOnlyReadOnly"); + } + + /// + /// Test the property 'Bar' + /// + [Test] + public void BarTest() + { + // TODO unit test for the property 'Bar' + } + /// + /// Test the property 'Foo' + /// + [Test] + public void FooTest() + { + // TODO unit test for the property 'Foo' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs new file mode 100644 index 00000000000..2d383b814b5 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ListTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing List + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ListTests + { + // TODO uncomment below to declare an instance variable for List + //private List instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of List + //instance = new List(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of List + /// + [Test] + public void ListInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" List + //Assert.IsInstanceOfType (instance, "variable 'instance' is a List"); + } + + /// + /// Test the property '_123List' + /// + [Test] + public void _123ListTest() + { + // TODO unit test for the property '_123List' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs new file mode 100644 index 00000000000..9cebfe18b24 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/MapTestTests.cs @@ -0,0 +1,86 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing MapTest + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class MapTestTests + { + // TODO uncomment below to declare an instance variable for MapTest + //private MapTest instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of MapTest + //instance = new MapTest(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of MapTest + /// + [Test] + public void MapTestInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" MapTest + //Assert.IsInstanceOfType (instance, "variable 'instance' is a MapTest"); + } + + /// + /// Test the property 'MapMapOfString' + /// + [Test] + public void MapMapOfStringTest() + { + // TODO unit test for the property 'MapMapOfString' + } + /// + /// Test the property 'MapOfEnumString' + /// + [Test] + public void MapOfEnumStringTest() + { + // TODO unit test for the property 'MapOfEnumString' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelClientTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelClientTests.cs new file mode 100644 index 00000000000..f38a3050940 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/ModelClientTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ModelClient + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ModelClientTests + { + // TODO uncomment below to declare an instance variable for ModelClient + //private ModelClient instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ModelClient + //instance = new ModelClient(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ModelClient + /// + [Test] + public void ModelClientInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ModelClient + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ModelClient"); + } + + /// + /// Test the property '_Client' + /// + [Test] + public void _ClientTest() + { + // TODO unit test for the property '_Client' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NumberOnlyTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NumberOnlyTests.cs new file mode 100644 index 00000000000..aecbedb83d3 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/NumberOnlyTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing NumberOnly + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class NumberOnlyTests + { + // TODO uncomment below to declare an instance variable for NumberOnly + //private NumberOnly instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of NumberOnly + //instance = new NumberOnly(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of NumberOnly + /// + [Test] + public void NumberOnlyInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" NumberOnly + //Assert.IsInstanceOfType (instance, "variable 'instance' is a NumberOnly"); + } + + /// + /// Test the property 'JustNumber' + /// + [Test] + public void JustNumberTest() + { + // TODO unit test for the property 'JustNumber' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OuterEnumTests.cs new file mode 100644 index 00000000000..e6bd10d185f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/OuterEnumTests.cs @@ -0,0 +1,70 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterEnumTests + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterEnum + /// + [Test] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterEnum + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnum"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs index 7d334bd58d9..52a26a00dbf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -108,7 +108,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); /// /// To test enum parameters @@ -126,7 +126,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Synchronous Operations #region Asynchronous Operations /// @@ -213,7 +213,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); /// /// To test enum parameters @@ -231,7 +231,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Asynchronous Operations } @@ -768,7 +768,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { TestEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } @@ -786,7 +786,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; @@ -856,7 +856,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { await TestEnumParametersAsyncWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -875,7 +875,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 55e00602e31..76d794700bf 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -6,13 +6,12 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git --> Debug AnyCPU - {CD650877-711F-40DC-9804-E09CE6CF93CE} + {108D4EC7-6EA0-4D25-A8EC-653076D76ADC} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs new file mode 100644 index 00000000000..d7947c69aba --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs @@ -0,0 +1,121 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model with \"_class\" property + /// + [DataContract] + public partial class ClassModel : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Class. + public ClassModel(string _Class = null) + { + this._Class = _Class; + } + + /// + /// Gets or Sets _Class + /// + [DataMember(Name="_class", EmitDefaultValue=false)] + public string _Class { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ClassModel {\n"); + sb.Append(" _Class: ").Append(_Class).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ClassModel); + } + + /// + /// Returns true if ClassModel instances are equal + /// + /// Instance of ClassModel to be compared + /// Boolean + public bool Equals(ClassModel other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._Class == other._Class || + this._Class != null && + this._Class.Equals(other._Class) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._Class != null) + hash = hash * 59 + this._Class.GetHashCode(); + return hash; + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs index 8ab6ea15af3..b486563bcaa 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -110,13 +110,20 @@ namespace IO.Swagger.Model /// EnumString. /// EnumInteger. /// EnumNumber. - public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) + /// OuterEnum. + public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null, OuterEnum? OuterEnum = null) { this.EnumString = EnumString; this.EnumInteger = EnumInteger; this.EnumNumber = EnumNumber; + this.OuterEnum = OuterEnum; } + /// + /// Gets or Sets OuterEnum + /// + [DataMember(Name="outerEnum", EmitDefaultValue=false)] + public OuterEnum? OuterEnum { get; set; } /// /// Returns the string presentation of the object /// @@ -128,6 +135,7 @@ namespace IO.Swagger.Model sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -178,6 +186,11 @@ namespace IO.Swagger.Model this.EnumNumber == other.EnumNumber || this.EnumNumber != null && this.EnumNumber.Equals(other.EnumNumber) + ) && + ( + this.OuterEnum == other.OuterEnum || + this.OuterEnum != null && + this.OuterEnum.Equals(other.OuterEnum) ); } @@ -198,6 +211,8 @@ namespace IO.Swagger.Model hash = hash * 59 + this.EnumInteger.GetHashCode(); if (this.EnumNumber != null) hash = hash * 59 + this.EnumNumber.GetHashCode(); + if (this.OuterEnum != null) + hash = hash * 59 + this.OuterEnum.GetHashCode(); return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index caa680763a6..de5cde20807 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -332,27 +332,27 @@ namespace IO.Swagger.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int?) maximum - if(this.Integer > (int?)100.0) + if(this.Integer > (int?)100) { - yield return new ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.0.", new [] { "Integer" }); + yield return new ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int?) minimum - if(this.Integer < (int?)10.0) + if(this.Integer < (int?)10) { - yield return new ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.0.", new [] { "Integer" }); + yield return new ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int?) maximum - if(this.Int32 > (int?)200.0) + if(this.Int32 > (int?)200) { - yield return new ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.0.", new [] { "Int32" }); + yield return new ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int?) minimum - if(this.Int32 < (int?)20.0) + if(this.Int32 < (int?)20) { - yield return new ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.0.", new [] { "Int32" }); + yield return new ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal?) maximum diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/OuterEnum.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/OuterEnum.cs new file mode 100644 index 00000000000..35c31cadfa6 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/OuterEnum.cs @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Defines OuterEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnum + { + + /// + /// Enum Placed for "placed" + /// + [EnumMember(Value = "placed")] + Placed, + + /// + /// Enum Approved for "approved" + /// + [EnumMember(Value = "approved")] + Approved, + + /// + /// Enum Delivered for "delivered" + /// + [EnumMember(Value = "delivered")] + Delivered + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/.travis.yml b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/.travis.yml index 4096e0b50d4..805caf43c2c 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/.travis.yml +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/.travis.yml @@ -1,18 +1,6 @@ # # Generated by: https://github.com/swagger-api/swagger-codegen.git # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# language: csharp mono: - latest diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln index f5367f2ba9d..8c223bc624d 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{2A56AF87-B694-4558-9CBC-D85E740D4BFD}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{2A56AF87-B694-4558-9CBC-D85E740D4BFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{2A56AF87-B694-4558-9CBC-D85E740D4BFD}.Debug|Any CPU.Build.0 = Debug|Any CPU -{2A56AF87-B694-4558-9CBC-D85E740D4BFD}.Release|Any CPU.ActiveCfg = Release|Any CPU -{2A56AF87-B694-4558-9CBC-D85E740D4BFD}.Release|Any CPU.Build.0 = Release|Any CPU +{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Debug|Any CPU.Build.0 = Debug|Any CPU +{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Release|Any CPU.ActiveCfg = Release|Any CPU +{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md index 8b5ee417fbb..67a001aa0cf 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md @@ -8,10 +8,12 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - SDK version: 1.0.0 - Build package: class io.swagger.codegen.languages.CSharpClientCodegen + ## Frameworks supported - .NET 4.0 or later - Windows Phone 7.1 (Mango) + ## Dependencies - [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later - [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later @@ -24,6 +26,7 @@ Install-Package Newtonsoft.Json NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742) + ## Installation Run the following command to generate the DLL - [Mac/Linux] `/bin/sh build.sh` @@ -33,9 +36,9 @@ Then include the DLL (under the `bin` folder) in the C# project, and use the nam ```csharp using IO.Swagger.Api; using IO.Swagger.Client; -using Model; +using IO.Swagger.Model; ``` - + ## Getting Started ```csharp @@ -43,7 +46,7 @@ using System; using System.Diagnostics; using IO.Swagger.Api; using IO.Swagger.Client; -using Model; +using IO.Swagger.Model; namespace Example { @@ -114,6 +117,7 @@ Class | Method | HTTP request | Description - [Model.ArrayTest](docs/ArrayTest.md) - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) + - [Model.ClassModel](docs/ClassModel.md) - [Model.Dog](docs/Dog.md) - [Model.EnumArrays](docs/EnumArrays.md) - [Model.EnumClass](docs/EnumClass.md) @@ -129,6 +133,7 @@ Class | Method | HTTP request | Description - [Model.Name](docs/Name.md) - [Model.NumberOnly](docs/NumberOnly.md) - [Model.Order](docs/Order.md) + - [Model.OuterEnum](docs/OuterEnum.md) - [Model.Pet](docs/Pet.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) - [Model.SpecialModelName](docs/SpecialModelName.md) @@ -136,6 +141,7 @@ Class | Method | HTTP request | Description - [Model.User](docs/User.md) + ## Documentation for Authorization diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat index ae94b120d7b..77508b858a0 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.bat @@ -1,22 +1,10 @@ :: Generated by: https://github.com/swagger-api/swagger-codegen.git :: -:: Licensed under the Apache License, Version 2.0 (the "License"); -:: you may not use this file except in compliance with the License. -:: You may obtain a copy of the License at -:: -:: http://www.apache.org/licenses/LICENSE-2.0 -:: -:: Unless required by applicable law or agreed to in writing, software -:: distributed under the License is distributed on an "AS IS" BASIS, -:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -:: See the License for the specific language governing permissions and -:: limitations under the License. @echo off SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 - if not exist ".\nuget.exe" powershell -Command "(new-object System.Net.WebClient).DownloadFile('https://nuget.org/nuget.exe', '.\nuget.exe')" .\nuget.exe install src\IO.Swagger\packages.config -o packages @@ -24,5 +12,8 @@ if not exist ".\bin" mkdir bin copy packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll bin\Newtonsoft.Json.dll copy packages\RestSharp.105.1.0\lib\net45\RestSharp.dll bin\RestSharp.dll +copy packages\Fody.1.29.2\Fody.dll bin\Fody.dll +copy packages\PropertyChanged.Fody.1.51.3\PropertyChanged.Fody.dll bin\PropertyChanged.Fody.dll +copy packages\PropertyChanged.Fody.1.51.3\Lib\dotnet\PropertyChanged.dll bin\PropertyChanged.dll +%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll;System.ComponentModel.DataAnnotations.dll /r:bin\Fody.dll;bin\PropertyChanged.Fody.dll;bin\PropertyChanged.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml -%CSCPATH%\csc /reference:bin\Newtonsoft.Json.dll;bin\RestSharp.dll /target:library /out:bin\IO.Swagger.dll /recurse:src\IO.Swagger\*.cs /doc:bin\IO.Swagger.xml diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh index b09ce1673fd..23dd920e8f8 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/build.sh @@ -2,17 +2,6 @@ # # Generated by: https://github.com/swagger-api/swagger-codegen.git # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. frameworkVersion=net45 netfx=${frameworkVersion#net} @@ -28,9 +17,15 @@ echo "[INFO] Copy DLLs to the 'bin' folder" mkdir -p bin; cp packages/Newtonsoft.Json.8.0.3/lib/net45/Newtonsoft.Json.dll bin/Newtonsoft.Json.dll; cp packages/RestSharp.105.1.0/lib/net45/RestSharp.dll bin/RestSharp.dll; +cp packages/Fody.1.29.2/Fody.dll bin/Fody.dll +cp packages/PropertyChanged.Fody.1.51.3/PropertyChanged.Fody.dll bin/PropertyChanged.Fody.dll +cp packages/PropertyChanged.Fody.1.51.3/Lib/dotnet/PropertyChanged.dll bin/PropertyChanged.dll echo "[INFO] Run 'mcs' to build bin/IO.Swagger.dll" mcs -sdk:${netfx} -r:bin/Newtonsoft.Json.dll,\ +bin/Fody.dll,\ +bin/PropertyChanged.Fody.dll,\ +bin/PropertyChanged.dll,\ bin/RestSharp.dll,\ System.ComponentModel.DataAnnotations.dll,\ System.Runtime.Serialization.dll \ diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ClassModel.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ClassModel.md new file mode 100644 index 00000000000..760130f053c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/ClassModel.md @@ -0,0 +1,9 @@ +# IO.Swagger.Model.ClassModel +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_Class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md index f0f300021b5..a4371a96695 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **EnumString** | **string** | | [optional] **EnumInteger** | **int?** | | [optional] **EnumNumber** | **double?** | | [optional] +**OuterEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md index 106daec81bf..8dd5de759ee 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md @@ -71,7 +71,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) +> void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -110,11 +110,12 @@ namespace Example var date = 2013-10-20; // DateTime? | None (optional) var dateTime = 2013-10-20T19:20:30+01:00; // DateTime? | None (optional) var password = password_example; // string | None (optional) + var callback = callback_example; // string | None (optional) try { // Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + apiInstance.TestEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); } catch (Exception e) { @@ -142,6 +143,7 @@ Name | Type | Description | Notes **date** | **DateTime?**| None | [optional] **dateTime** | **DateTime?**| None | [optional] **password** | **string**| None | [optional] + **callback** | **string**| None | [optional] ### Return type @@ -160,7 +162,7 @@ void (empty response body) # **TestEnumParameters** -> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) +> void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) To test enum parameters @@ -186,7 +188,7 @@ namespace Example var enumHeaderString = enumHeaderString_example; // string | Header parameter enum test (string) (optional) (default to -efg) var enumQueryStringArray = new List(); // List | Query parameter enum test (string array) (optional) var enumQueryString = enumQueryString_example; // string | Query parameter enum test (string) (optional) (default to -efg) - var enumQueryInteger = 3.4; // decimal? | Query parameter enum test (double) (optional) + var enumQueryInteger = 56; // int? | Query parameter enum test (double) (optional) var enumQueryDouble = 1.2; // double? | Query parameter enum test (double) (optional) try @@ -213,7 +215,7 @@ Name | Type | Description | Notes **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] - **enumQueryInteger** | **decimal?**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **int?**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] ### Return type @@ -226,8 +228,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json - - **Accept**: application/json + - **Content-Type**: */* + - **Accept**: */* [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/OuterEnum.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/OuterEnum.md new file mode 100644 index 00000000000..55eb118a349 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/OuterEnum.md @@ -0,0 +1,8 @@ +# IO.Swagger.Model.OuterEnum +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh index 602b9727d2c..6e094f7c0d1 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/mono_nunit_test.sh @@ -2,17 +2,6 @@ # # Generated by: https://github.com/swagger-api/swagger-codegen.git # -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. wget -nc https://nuget.org/nuget.exe mozroots --import --sync diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj index 3a17bc59a9d..b5bb96e8e4b 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -6,19 +6,6 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. --> @@ -87,7 +74,7 @@ limitations under the License. - {2A56AF87-B694-4558-9CBC-D85E740D4BFD} + {4B8145C1-32ED-46D4-9DD5-10A82B5B0013} IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ClassModelTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ClassModelTests.cs new file mode 100644 index 00000000000..01b2c5b9c1b --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/ClassModelTests.cs @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing ClassModel + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class ClassModelTests + { + // TODO uncomment below to declare an instance variable for ClassModel + //private ClassModel instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of ClassModel + //instance = new ClassModel(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of ClassModel + /// + [Test] + public void ClassModelInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" ClassModel + //Assert.IsInstanceOfType (instance, "variable 'instance' is a ClassModel"); + } + + /// + /// Test the property '_Class' + /// + [Test] + public void _ClassTest() + { + // TODO unit test for the property '_Class' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OuterEnumTests.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OuterEnumTests.cs new file mode 100644 index 00000000000..e6bd10d185f --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/Model/OuterEnumTests.cs @@ -0,0 +1,70 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing OuterEnum + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class OuterEnumTests + { + // TODO uncomment below to declare an instance variable for OuterEnum + //private OuterEnum instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of OuterEnum + //instance = new OuterEnum(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of OuterEnum + /// + [Test] + public void OuterEnumInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" OuterEnum + //Assert.IsInstanceOfType (instance, "variable 'instance' is a OuterEnum"); + } + + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs index f6d4c85a6ce..52a26a00dbf 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; @@ -77,8 +65,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// - void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -100,8 +89,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null); /// /// To test enum parameters /// @@ -118,7 +108,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); /// /// To test enum parameters @@ -136,7 +126,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Synchronous Operations #region Asynchronous Operations /// @@ -180,8 +170,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -203,8 +194,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null); + System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null); /// /// To test enum parameters /// @@ -221,7 +213,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); /// /// To test enum parameters @@ -239,7 +231,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null); + System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null); #endregion Asynchronous Operations } @@ -526,10 +518,11 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// - public void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public void TestEndpointParameters (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) { - TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + TestEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); } /// @@ -549,8 +542,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// ApiResponse of Object(void) - public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public ApiResponse TestEndpointParametersWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) { // verify the required parameter 'number' is set if (number == null) @@ -605,6 +599,7 @@ namespace IO.Swagger.Api if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + if (callback != null) localVarFormParams.Add("callback", Configuration.ApiClient.ParameterToString(callback)); // form parameter // authentication (http_basic_test) required // http basic authentication required @@ -650,10 +645,11 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task TestEndpointParametersAsync (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) { - await TestEndpointParametersAsyncWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password); + await TestEndpointParametersAsyncWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, _string, binary, date, dateTime, password, callback); } @@ -674,8 +670,9 @@ namespace IO.Swagger.Api /// None (optional) /// None (optional) /// None (optional) + /// None (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null) + public async System.Threading.Tasks.Task> TestEndpointParametersAsyncWithHttpInfo (decimal? number, double? _double, string patternWithoutDelimiter, byte[] _byte, int? integer = null, int? int32 = null, long? int64 = null, float? _float = null, string _string = null, byte[] binary = null, DateTime? date = null, DateTime? dateTime = null, string password = null, string callback = null) { // verify the required parameter 'number' is set if (number == null) @@ -730,6 +727,7 @@ namespace IO.Swagger.Api if (date != null) localVarFormParams.Add("date", Configuration.ApiClient.ParameterToString(date)); // form parameter if (dateTime != null) localVarFormParams.Add("dateTime", Configuration.ApiClient.ParameterToString(dateTime)); // form parameter if (password != null) localVarFormParams.Add("password", Configuration.ApiClient.ParameterToString(password)); // form parameter + if (callback != null) localVarFormParams.Add("callback", Configuration.ApiClient.ParameterToString(callback)); // form parameter // authentication (http_basic_test) required // http basic authentication required @@ -770,7 +768,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// - public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public void TestEnumParameters (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { TestEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); } @@ -788,7 +786,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// ApiResponse of Object(void) - public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public ApiResponse TestEnumParametersWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; @@ -801,13 +799,13 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { - "application/json" + "*/*" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { - "application/json" + "*/*" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) @@ -858,7 +856,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of void - public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task TestEnumParametersAsync (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { await TestEnumParametersAsyncWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -877,7 +875,7 @@ namespace IO.Swagger.Api /// Query parameter enum test (double) (optional) /// Query parameter enum test (double) (optional) /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, decimal? enumQueryInteger = null, double? enumQueryDouble = null) + public async System.Threading.Tasks.Task> TestEnumParametersAsyncWithHttpInfo (List enumFormStringArray = null, string enumFormString = null, List enumHeaderStringArray = null, string enumHeaderString = null, List enumQueryStringArray = null, string enumQueryString = null, int? enumQueryInteger = null, double? enumQueryDouble = null) { var localVarPath = "/fake"; @@ -890,13 +888,13 @@ namespace IO.Swagger.Api // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { - "application/json" + "*/*" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { - "application/json" + "*/*" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs index fdf4b752799..d28c2e4fe2e 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/PetApi.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs index 668bb7819b4..c9c9461bc60 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/StoreApi.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs index 1865ec1631d..f05fc22dcca 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/UserApi.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs index 5aaf146d69e..14f156f7e35 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiClient.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs index 1afc1529a75..79c6432ffc6 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiException.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs index 03c64ab42e2..b21347aa408 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ApiResponse.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs index 12f87d6e6fa..2cb84a0c076 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs index 129e591f8a7..31b270ea0ff 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs index 845e6a49e9b..20f9722af2a 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/IApiAccessor.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj index 7827cb719dc..29b0fdbc6f1 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj @@ -6,25 +6,12 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io -Generated by: https://github.com/swagger-api/swagger-codegen.git - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. --> Debug AnyCPU - {2A56AF87-B694-4558-9CBC-D85E740D4BFD} + {4B8145C1-32ED-46D4-9DD5-10A82B5B0013} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs index 875e2eed2ce..03f64731a5c 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs index 97fee42a3a4..204454aa060 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs index 6febf5ed135..c2acd5d3464 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AnimalFarm.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs index ebbcad265c4..62fd27efd83 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs index ac5ac025933..94f61cac428 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs index 7aa16298467..1f7c93a7118 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs index b13880edacd..9fd2075fdc7 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs index 1120e2faf92..797bfd287be 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs index 27e980bc721..38dac8187e0 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs new file mode 100644 index 00000000000..369efd6a4d8 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs @@ -0,0 +1,137 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Model for testing model with \"_class\" property + /// + [DataContract] + [ImplementPropertyChanged] + public partial class ClassModel : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// _Class. + public ClassModel(string _Class = null) + { + this._Class = _Class; + } + + /// + /// Gets or Sets _Class + /// + [DataMember(Name="_class", EmitDefaultValue=false)] + public string _Class { get; set; } + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ClassModel {\n"); + sb.Append(" _Class: ").Append(_Class).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as ClassModel); + } + + /// + /// Returns true if ClassModel instances are equal + /// + /// Instance of ClassModel to be compared + /// Boolean + public bool Equals(ClassModel other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this._Class == other._Class || + this._Class != null && + this._Class.Equals(other._Class) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this._Class != null) + hash = hash * 59 + this._Class.GetHashCode(); + return hash; + } + } + + public event PropertyChangedEventHandler PropertyChanged; + + public virtual void OnPropertyChanged(string propertyName) + { + // NOTE: property changed is handled via "code weaving" using Fody. + // Properties with setters are modified at compile time to notify of changes. + var propertyChanged = PropertyChanged; + if (propertyChanged != null) + { + propertyChanged(this, new PropertyChangedEventArgs(propertyName)); + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs index 8e834c85e6a..1f116a03efc 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs index faa2f74a1c6..f41fd9845ac 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs index 60432e1d3bf..d61c056ad36 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumClass.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs index b2c9e8e8e2e..b4e8247da55 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; @@ -125,13 +113,20 @@ namespace IO.Swagger.Model /// EnumString. /// EnumInteger. /// EnumNumber. - public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null) + /// OuterEnum. + public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null, OuterEnum? OuterEnum = null) { this.EnumString = EnumString; this.EnumInteger = EnumInteger; this.EnumNumber = EnumNumber; + this.OuterEnum = OuterEnum; } + /// + /// Gets or Sets OuterEnum + /// + [DataMember(Name="outerEnum", EmitDefaultValue=false)] + public OuterEnum? OuterEnum { get; set; } /// /// Returns the string presentation of the object /// @@ -143,6 +138,7 @@ namespace IO.Swagger.Model sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -193,6 +189,11 @@ namespace IO.Swagger.Model this.EnumNumber == other.EnumNumber || this.EnumNumber != null && this.EnumNumber.Equals(other.EnumNumber) + ) && + ( + this.OuterEnum == other.OuterEnum || + this.OuterEnum != null && + this.OuterEnum.Equals(other.OuterEnum) ); } @@ -213,6 +214,8 @@ namespace IO.Swagger.Model hash = hash * 59 + this.EnumInteger.GetHashCode(); if (this.EnumNumber != null) hash = hash * 59 + this.EnumNumber.GetHashCode(); + if (this.OuterEnum != null) + hash = hash * 59 + this.OuterEnum.GetHashCode(); return hash; } } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs index e00fdf2f745..e415fa64925 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; @@ -360,27 +348,27 @@ namespace IO.Swagger.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int?) maximum - if(this.Integer > (int?)100.0) + if(this.Integer > (int?)100) { - yield return new ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.0.", new [] { "Integer" }); + yield return new ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int?) minimum - if(this.Integer < (int?)10.0) + if(this.Integer < (int?)10) { - yield return new ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.0.", new [] { "Integer" }); + yield return new ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int?) maximum - if(this.Int32 > (int?)200.0) + if(this.Int32 > (int?)200) { - yield return new ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.0.", new [] { "Int32" }); + yield return new ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int?) minimum - if(this.Int32 < (int?)20.0) + if(this.Int32 < (int?)20) { - yield return new ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.0.", new [] { "Int32" }); + yield return new ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal?) maximum diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs index 4fc798b7e70..2ba454b2845 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/HasOnlyReadOnly.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs index c9f6b6be4f9..95d18430713 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs index 243c855b4fd..f2dfce4e57f 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 61adb990383..d0c7a54f1df 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs index 0e6db28041e..b838abe9f73 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs index 3d0f1af2ab7..675b3b82fc5 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs index a092e681b5c..fad3b1eab8a 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs index 31ebcde8efa..c561bcb3408 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs index d3d5e5d3090..379ecb93c79 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs index 1bf61b11df8..a8e7af069b8 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/OuterEnum.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/OuterEnum.cs new file mode 100644 index 00000000000..9588d8086ec --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/OuterEnum.cs @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using PropertyChanged; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Defines OuterEnum + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum OuterEnum + { + + /// + /// Enum Placed for "placed" + /// + [EnumMember(Value = "placed")] + Placed, + + /// + /// Enum Approved for "approved" + /// + [EnumMember(Value = "approved")] + Approved, + + /// + /// Enum Delivered for "delivered" + /// + [EnumMember(Value = "delivered")] + Delivered + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs index c20ec7c1106..ea6243170c1 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs index 4039c2bd3ee..961cf1eb13e 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs index 7545aa5fa36..2c0013cf6f3 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs index 54c13750f91..1c0597818ae 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs index 988ec591edf..316b7feb2cc 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs @@ -6,18 +6,6 @@ * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io * Generated by: https://github.com/swagger-api/swagger-codegen.git - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ using System; From 73bf589ad0e1e1f0219299316d6795d66723a4f2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Dec 2016 15:18:55 +0800 Subject: [PATCH 143/269] add swagger codegen evangelist --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 7e3cd797b9b..95e0bb1e6d8 100644 --- a/README.md +++ b/README.md @@ -941,6 +941,12 @@ Swagger Codegen Evangelist shoulders one or more of the following responsibiliti If you want to be a Swagger Codegen Evangelist, please kindly apply by sending an email to wing328hk@gmail.com (@wing328) +### List of Swagger Codegen Evangelists + +- Cliffano Subagio (@cliffano from Australia joined on Dec 9, 2016) + - [Building An AEM API Clients Ecosystem](http://www.slideshare.net/cliffano/building-an-aem-api-clients-ecosystem) + - [Adobe Marketing Cloud Community Expo](http://blog.cliffano.com/2016/11/10/adobe-marketing-cloud-community-expo/) + # License information on Generated Code The Swagger Codegen project is intended as a benefit for users of the Swagger / Open API Specification. The project itself has the [License](#license) as specified. In addition, please understand the following points: From c3571b28a5be8baa1a37c6df434c931493b7b206 Mon Sep 17 00:00:00 2001 From: Jens Oberender Date: Fri, 9 Dec 2016 08:55:33 +0100 Subject: [PATCH 144/269] Some code cleanings of problems reported by SonarQube. (#4324) * Some code cleanings of problems reported by SonarQube. * Updated changes to the petshop sample. --- .../main/resources/Java/ApiClient.mustache | 16 ++++---- .../Java/libraries/jersey2/ApiClient.mustache | 41 ++++++++++--------- samples/client/petstore/java/feign/hello.txt | 1 - .../java/io/swagger/client/ApiClient.java | 16 ++++---- .../java/io/swagger/client/ApiClient.java | 41 ++++++++++--------- .../client/petstore/java/jersey2/hello.txt | 1 - .../java/io/swagger/client/ApiClient.java | 41 ++++++++++--------- .../client/petstore/java/retrofit/hello.txt | 1 - 8 files changed, 79 insertions(+), 79 deletions(-) delete mode 100644 samples/client/petstore/java/feign/hello.txt delete mode 100644 samples/client/petstore/java/jersey2/hello.txt delete mode 100644 samples/client/petstore/java/retrofit/hello.txt diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index c34dd51dcea..25aa9099ef2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -353,7 +353,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { - b.append(","); + b.append(','); } b.append(String.valueOf(o)); } @@ -372,7 +372,7 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; + Collection valueCollection; if (value instanceof Collection) { valueCollection = (Collection) value; } else { @@ -385,10 +385,10 @@ public class ApiClient { } // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format - if (collectionFormat.equals("multi")) { + if ("multi".equals(format)) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } @@ -398,13 +398,13 @@ public class ApiClient { String delimiter = ","; - if (collectionFormat.equals("csv")) { + if ("csv".equals(format)) { delimiter = ","; - } else if (collectionFormat.equals("ssv")) { + } else if ("ssv".equals(format)) { delimiter = " "; - } else if (collectionFormat.equals("tsv")) { + } else if ("tsv".equals(format)) { delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { + } else if ("pipes".equals(format)) { delimiter = "|"; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 668b34a90ae..b81cd18d37f 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -329,7 +329,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { - b.append(","); + b.append(','); } b.append(String.valueOf(o)); } @@ -348,7 +348,7 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; + Collection valueCollection; if (value instanceof Collection) { valueCollection = (Collection) value; } else { @@ -361,10 +361,10 @@ public class ApiClient { } // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format - if (collectionFormat.equals("multi")) { + if ("multi".equals(format)) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } @@ -374,13 +374,13 @@ public class ApiClient { String delimiter = ","; - if (collectionFormat.equals("csv")) { + if ("csv".equals(format)) { delimiter = ","; - } else if (collectionFormat.equals("ssv")) { + } else if ("ssv".equals(format)) { delimiter = " "; - } else if (collectionFormat.equals("tsv")) { + } else if ("tsv".equals(format)) { delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { + } else if ("pipes".equals(format)) { delimiter = "|"; } @@ -464,7 +464,7 @@ public class ApiClient { * Content-Type (only JSON is supported for now). */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { - Entity entity = null; + Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { @@ -495,6 +495,7 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -503,9 +504,8 @@ public class ApiClient { if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). return (T) response.readEntity(byte[].class); - } else if (returnType.equals(File.class)) { + } else if (returnType.getRawType() == File.class) { // Handle file downloading. - @SuppressWarnings("unchecked") T file = (T) downloadFileFromResponse(response); return file; } @@ -551,13 +551,13 @@ public class ApiClient { filename = matcher.group(1); } - String prefix = null; + String prefix; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { - int pos = filename.lastIndexOf("."); + int pos = filename.lastIndexOf('.'); if (pos == -1) { prefix = filename + "-"; } else { @@ -607,16 +607,17 @@ public class ApiClient { Invocation.Builder invocationBuilder = target.request().accept(accept); - for (String key : headerParams.keySet()) { - String value = headerParams.get(key); + for (Entry entry : headerParams.entrySet()) { + String value = entry.getValue(); if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); + invocationBuilder = invocationBuilder.header(entry.getKey(), value); } } - for (String key : defaultHeaderMap.keySet()) { + for (Entry entry : defaultHeaderMap.entrySet()) { + String key = entry.getKey(); if (!headerParams.containsKey(key)) { - String value = defaultHeaderMap.get(key); + String value = entry.getValue(); if (value != null) { invocationBuilder = invocationBuilder.header(key, value); } @@ -625,7 +626,7 @@ public class ApiClient { Entity entity = serialize(body, formParams, contentType); - Response response = null; + Response response; if ("GET".equals(method)) { response = invocationBuilder.get(); @@ -646,7 +647,7 @@ public class ApiClient { if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { if (returnType == null) return null; else diff --git a/samples/client/petstore/java/feign/hello.txt b/samples/client/petstore/java/feign/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/feign/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index 841ae1112eb..36792292bdc 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -354,7 +354,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { - b.append(","); + b.append(','); } b.append(String.valueOf(o)); } @@ -373,7 +373,7 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; + Collection valueCollection; if (value instanceof Collection) { valueCollection = (Collection) value; } else { @@ -386,10 +386,10 @@ public class ApiClient { } // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format - if (collectionFormat.equals("multi")) { + if ("multi".equals(format)) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } @@ -399,13 +399,13 @@ public class ApiClient { String delimiter = ","; - if (collectionFormat.equals("csv")) { + if ("csv".equals(format)) { delimiter = ","; - } else if (collectionFormat.equals("ssv")) { + } else if ("ssv".equals(format)) { delimiter = " "; - } else if (collectionFormat.equals("tsv")) { + } else if ("tsv".equals(format)) { delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { + } else if ("pipes".equals(format)) { delimiter = "|"; } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index 5eb7e89e13e..adec2801d00 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -324,7 +324,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { - b.append(","); + b.append(','); } b.append(String.valueOf(o)); } @@ -343,7 +343,7 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; + Collection valueCollection; if (value instanceof Collection) { valueCollection = (Collection) value; } else { @@ -356,10 +356,10 @@ public class ApiClient { } // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format - if (collectionFormat.equals("multi")) { + if ("multi".equals(format)) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } @@ -369,13 +369,13 @@ public class ApiClient { String delimiter = ","; - if (collectionFormat.equals("csv")) { + if ("csv".equals(format)) { delimiter = ","; - } else if (collectionFormat.equals("ssv")) { + } else if ("ssv".equals(format)) { delimiter = " "; - } else if (collectionFormat.equals("tsv")) { + } else if ("tsv".equals(format)) { delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { + } else if ("pipes".equals(format)) { delimiter = "|"; } @@ -459,7 +459,7 @@ public class ApiClient { * Content-Type (only JSON is supported for now). */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { - Entity entity = null; + Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { @@ -490,6 +490,7 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -498,9 +499,8 @@ public class ApiClient { if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). return (T) response.readEntity(byte[].class); - } else if (returnType.equals(File.class)) { + } else if (returnType.getRawType() == File.class) { // Handle file downloading. - @SuppressWarnings("unchecked") T file = (T) downloadFileFromResponse(response); return file; } @@ -540,13 +540,13 @@ public class ApiClient { filename = matcher.group(1); } - String prefix = null; + String prefix; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { - int pos = filename.lastIndexOf("."); + int pos = filename.lastIndexOf('.'); if (pos == -1) { prefix = filename + "-"; } else { @@ -596,16 +596,17 @@ public class ApiClient { Invocation.Builder invocationBuilder = target.request().accept(accept); - for (String key : headerParams.keySet()) { - String value = headerParams.get(key); + for (Entry entry : headerParams.entrySet()) { + String value = entry.getValue(); if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); + invocationBuilder = invocationBuilder.header(entry.getKey(), value); } } - for (String key : defaultHeaderMap.keySet()) { + for (Entry entry : defaultHeaderMap.entrySet()) { + String key = entry.getKey(); if (!headerParams.containsKey(key)) { - String value = defaultHeaderMap.get(key); + String value = entry.getValue(); if (value != null) { invocationBuilder = invocationBuilder.header(key, value); } @@ -614,7 +615,7 @@ public class ApiClient { Entity entity = serialize(body, formParams, contentType); - Response response = null; + Response response; if ("GET".equals(method)) { response = invocationBuilder.get(); @@ -635,7 +636,7 @@ public class ApiClient { if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { if (returnType == null) return null; else diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/jersey2/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 5eb7e89e13e..adec2801d00 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -324,7 +324,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); for(Object o : (Collection)param) { if(b.length() > 0) { - b.append(","); + b.append(','); } b.append(String.valueOf(o)); } @@ -343,7 +343,7 @@ public class ApiClient { // preconditions if (name == null || name.isEmpty() || value == null) return params; - Collection valueCollection = null; + Collection valueCollection; if (value instanceof Collection) { valueCollection = (Collection) value; } else { @@ -356,10 +356,10 @@ public class ApiClient { } // get the collection format - collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv // create the params based on the collection format - if (collectionFormat.equals("multi")) { + if ("multi".equals(format)) { for (Object item : valueCollection) { params.add(new Pair(name, parameterToString(item))); } @@ -369,13 +369,13 @@ public class ApiClient { String delimiter = ","; - if (collectionFormat.equals("csv")) { + if ("csv".equals(format)) { delimiter = ","; - } else if (collectionFormat.equals("ssv")) { + } else if ("ssv".equals(format)) { delimiter = " "; - } else if (collectionFormat.equals("tsv")) { + } else if ("tsv".equals(format)) { delimiter = "\t"; - } else if (collectionFormat.equals("pipes")) { + } else if ("pipes".equals(format)) { delimiter = "|"; } @@ -459,7 +459,7 @@ public class ApiClient { * Content-Type (only JSON is supported for now). */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { - Entity entity = null; + Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { @@ -490,6 +490,7 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. */ + @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { if (response == null || returnType == null) { return null; @@ -498,9 +499,8 @@ public class ApiClient { if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). return (T) response.readEntity(byte[].class); - } else if (returnType.equals(File.class)) { + } else if (returnType.getRawType() == File.class) { // Handle file downloading. - @SuppressWarnings("unchecked") T file = (T) downloadFileFromResponse(response); return file; } @@ -540,13 +540,13 @@ public class ApiClient { filename = matcher.group(1); } - String prefix = null; + String prefix; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { - int pos = filename.lastIndexOf("."); + int pos = filename.lastIndexOf('.'); if (pos == -1) { prefix = filename + "-"; } else { @@ -596,16 +596,17 @@ public class ApiClient { Invocation.Builder invocationBuilder = target.request().accept(accept); - for (String key : headerParams.keySet()) { - String value = headerParams.get(key); + for (Entry entry : headerParams.entrySet()) { + String value = entry.getValue(); if (value != null) { - invocationBuilder = invocationBuilder.header(key, value); + invocationBuilder = invocationBuilder.header(entry.getKey(), value); } } - for (String key : defaultHeaderMap.keySet()) { + for (Entry entry : defaultHeaderMap.entrySet()) { + String key = entry.getKey(); if (!headerParams.containsKey(key)) { - String value = defaultHeaderMap.get(key); + String value = entry.getValue(); if (value != null) { invocationBuilder = invocationBuilder.header(key, value); } @@ -614,7 +615,7 @@ public class ApiClient { Entity entity = serialize(body, formParams, contentType); - Response response = null; + Response response; if ("GET".equals(method)) { response = invocationBuilder.get(); @@ -635,7 +636,7 @@ public class ApiClient { if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; - } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { if (returnType == null) return null; else diff --git a/samples/client/petstore/java/retrofit/hello.txt b/samples/client/petstore/java/retrofit/hello.txt deleted file mode 100644 index 6769dd60bdf..00000000000 --- a/samples/client/petstore/java/retrofit/hello.txt +++ /dev/null @@ -1 +0,0 @@ -Hello world! \ No newline at end of file From 4d2a13018b22f880e6638b9d212a5bb2ab06a2ef Mon Sep 17 00:00:00 2001 From: Vlad Frolov Date: Fri, 9 Dec 2016 11:26:23 +0200 Subject: [PATCH 145/269] [Python] Make the code look Pythonic (#4352) --- .../main/resources/python/api_client.mustache | 100 +++++----- .../python/petstore_api/__init__.py | 13 +- .../python/petstore_api/api_client.py | 171 ++++++++++-------- .../python/petstore_api/apis/fake_api.py | 43 ++--- .../python/petstore_api/configuration.py | 13 +- .../python/petstore_api/models/__init__.py | 13 +- .../petstore_api/models/model_return.py | 14 +- .../python/petstore_api/rest.py | 87 ++++++--- .../petstore-security-test/python/setup.py | 15 +- samples/client/petstore/python/README.md | 1 + .../client/petstore/python/docs/ClassModel.md | 10 + .../client/petstore/python/docs/FakeApi.md | 4 +- .../petstore/python/petstore_api/__init__.py | 1 + .../python/petstore_api/api_client.py | 100 +++++----- .../python/petstore_api/apis/fake_api.py | 20 +- .../python/petstore_api/apis/store_api.py | 8 +- .../python/petstore_api/models/__init__.py | 1 + .../python/petstore_api/models/class_model.py | 112 ++++++++++++ .../python/petstore_api/models/format_test.py | 16 +- .../petstore/python/test/test_class_model.py | 42 +++++ 20 files changed, 471 insertions(+), 313 deletions(-) create mode 100644 samples/client/petstore/python/docs/ClassModel.md create mode 100644 samples/client/petstore/python/petstore_api/models/class_model.py create mode 100644 samples/client/petstore/python/test/test_class_model.py diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 6b1a7d7e61b..eb8b73c7bdf 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -1,13 +1,7 @@ # coding: utf-8 - {{>partial_header}} - from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -15,14 +9,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -42,8 +37,20 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -144,7 +151,10 @@ class ApiClient(object): return_data = None if callback: - callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: return (return_data) else: @@ -165,10 +175,9 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) @@ -178,21 +187,21 @@ class ApiClient(object): for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -206,7 +215,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -241,17 +250,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -451,7 +455,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -468,7 +472,7 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' @@ -538,12 +542,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -568,8 +571,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -589,8 +591,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -608,7 +612,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore-security-test/python/petstore_api/__init__.py b/samples/client/petstore-security-test/python/petstore_api/__init__.py index 6bfb00016ef..a8cf9ed66eb 100644 --- a/samples/client/petstore-security-test/python/petstore_api/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/__init__.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import # import models into sdk package diff --git a/samples/client/petstore-security-test/python/petstore_api/api_client.py b/samples/client/petstore-security-test/python/petstore_api/api_client.py index adf66173dbc..02c6172ccc4 100644 --- a/samples/client/petstore-security-test/python/petstore_api/api_client.py +++ b/samples/client/petstore-security-test/python/petstore_api/api_client.py @@ -1,29 +1,16 @@ # coding: utf-8 - """ -Copyright 2016 SmartBear Software + Swagger Petstore */ ' \" =end -- \\r\\n \\n \\r - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - - ref: https://github.com/swagger-api/swagger-codegen + OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r + Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r + Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -31,14 +18,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -58,8 +46,20 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -96,7 +96,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): # header parameters header_params = header_params or {} @@ -144,22 +145,29 @@ class ApiClient(object): response_data = self.request(method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body) + post_params=post_params, body=body, + _preload_content=_preload_content, + _request_timeout=_request_timeout) self.last_response = response_data - # deserialize response data - if response_type: - deserialized_data = self.deserialize(response_data, response_type) - else: - deserialized_data = None + return_data = response_data + if _preload_content: + # deserialize response data + if response_type: + return_data = self.deserialize(response_data, response_type) + else: + return_data = None if callback: - callback(deserialized_data) if _return_http_data_only else callback((deserialized_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: - return (deserialized_data) + return (return_data) else: - return (deserialized_data, response_data.status, response_data.getheaders()) + return (return_data, response_data.status, response_data.getheaders()) def sanitize_for_serialization(self, obj): """ @@ -176,34 +184,33 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, tuple): return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -217,7 +224,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -252,17 +259,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -277,7 +279,8 @@ class ApiClient(object): path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None, - _return_http_data_only=None, collection_formats=None): + _return_http_data_only=None, collection_formats=None, _preload_content=True, + _request_timeout=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. @@ -301,6 +304,10 @@ class ApiClient(object): :param _return_http_data_only: response data without head status code and headers :param collection_formats: dict of collection formats for path, query, header, and post parameters. + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. :return: If provide parameter callback, the request will be called asynchronously. @@ -313,7 +320,7 @@ class ApiClient(object): path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback, - _return_http_data_only, collection_formats) + _return_http_data_only, collection_formats, _preload_content, _request_timeout) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, @@ -322,51 +329,65 @@ class ApiClient(object): post_params, files, response_type, auth_settings, callback, _return_http_data_only, - collection_formats)) + collection_formats, _preload_content, _request_timeout)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None): + post_params=None, body=None, _preload_content=True, _request_timeout=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) else: raise ValueError( @@ -443,7 +464,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -460,9 +481,9 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] - if 'application/json' in content_types: + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: return content_types[0] @@ -530,12 +551,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -560,8 +580,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -581,8 +600,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -600,7 +621,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py index b2a58f84e7b..f713d227c0e 100644 --- a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import sys @@ -54,8 +43,6 @@ class FakeApi(object): def test_code_inject____end__rn_n_r(self, **kwargs): """ To test code injection */ ' \" =end -- \\r\\n \\n \\r - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -81,8 +68,6 @@ class FakeApi(object): def test_code_inject____end__rn_n_r_with_http_info(self, **kwargs): """ To test code injection */ ' \" =end -- \\r\\n \\n \\r - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -102,6 +87,8 @@ class FakeApi(object): all_params = ['test_code_inject____end____rn_n_r'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -144,14 +131,16 @@ class FakeApi(object): auth_settings = [] return self.api_client.call_api(resource_path, 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type=None, + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore-security-test/python/petstore_api/configuration.py b/samples/client/petstore-security-test/python/petstore_api/configuration.py index b612f103532..55b00220da5 100644 --- a/samples/client/petstore-security-test/python/petstore_api/configuration.py +++ b/samples/client/petstore-security-test/python/petstore_api/configuration.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import urllib3 diff --git a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py index d5006ee92c6..a75a00eb198 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/__init__.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/__init__.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import # import models into model package diff --git a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py index 886ec0d5601..8256e70ca94 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from pprint import pformat from six import iteritems import re @@ -51,7 +40,6 @@ class ModelReturn(object): self.__return = _return - @property def _return(self): """ diff --git a/samples/client/petstore-security-test/python/petstore_api/rest.py b/samples/client/petstore-security-test/python/petstore_api/rest.py index fc6b878837c..2c54f4ceae8 100644 --- a/samples/client/petstore-security-test/python/petstore_api/rest.py +++ b/samples/client/petstore-security-test/python/petstore_api/rest.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + from __future__ import absolute_import import io @@ -69,10 +58,11 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): - def __init__(self, pools_size=4): + def __init__(self, pools_size=4, maxsize=4): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # maxsize is the number of requests to host that are allowed in parallel # ca_certs vs cert_file vs key_file # http://stackoverflow.com/a/23957365/2985775 @@ -98,6 +88,7 @@ class RESTClientObject(object): # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, + maxsize=maxsize, cert_reqs=cert_reqs, ca_certs=ca_certs, cert_file=cert_file, @@ -105,7 +96,7 @@ class RESTClientObject(object): ) def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None): + body=None, post_params=None, _preload_content=True, _request_timeout=None): """ :param method: http request method :param url: http request url @@ -115,6 +106,10 @@ class RESTClientObject(object): :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` + :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without + reading/decoding response data. Default is True. + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request + timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] @@ -127,6 +122,13 @@ class RESTClientObject(object): post_params = post_params or {} headers = headers or {} + timeout = None + if _request_timeout: + if isinstance(_request_timeout, (int, ) if PY3 else (int, long)): + timeout = urllib3.Timeout(total=_request_timeout) + elif isinstance(_request_timeout, tuple) and len(_request_timeout) == 2: + timeout = urllib3.Timeout(connect=_request_timeout[0], read=_request_timeout[1]) + if 'Content-Type' not in headers: headers['Content-Type'] = 'application/json' @@ -141,11 +143,15 @@ class RESTClientObject(object): request_body = json.dumps(body) r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'application/x-www-form-urlencoded': r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=False, + preload_content=_preload_content, + timeout=timeout, headers=headers) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct Content-Type @@ -154,6 +160,8 @@ class RESTClientObject(object): r = self.pool_manager.request(method, url, fields=post_params, encode_multipart=True, + preload_content=_preload_content, + timeout=timeout, headers=headers) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is provided @@ -162,6 +170,8 @@ class RESTClientObject(object): request_body = body r = self.pool_manager.request(method, url, body=request_body, + preload_content=_preload_content, + timeout=timeout, headers=headers) else: # Cannot generate the request from given parameters @@ -172,68 +182,89 @@ class RESTClientObject(object): else: r = self.pool_manager.request(method, url, fields=query_params, + preload_content=_preload_content, + timeout=timeout, headers=headers) except urllib3.exceptions.SSLError as e: msg = "{0}\n{1}".format(type(e).__name__, str(e)) raise ApiException(status=0, reason=msg) - r = RESTResponse(r) + if _preload_content: + r = RESTResponse(r) - # In the python 3, the response.data is bytes. - # we need to decode it to string. - if PY3: - r.data = r.data.decode('utf8') + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if PY3: + r.data = r.data.decode('utf8') - # log response body - logger.debug("response body: %s", r.data) + # log response body + logger.debug("response body: %s", r.data) if r.status not in range(200, 206): raise ApiException(http_resp=r) return r - def GET(self, url, headers=None, query_params=None): + def GET(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("GET", url, headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def HEAD(self, url, headers=None, query_params=None): + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, _request_timeout=None): return self.request("HEAD", url, headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("OPTIONS", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def DELETE(self, url, headers=None, query_params=None, body=None): + def DELETE(self, url, headers=None, query_params=None, body=None, _preload_content=True, _request_timeout=None): return self.request("DELETE", url, headers=headers, query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def POST(self, url, headers=None, query_params=None, post_params=None, body=None): + def POST(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("POST", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PUT(self, url, headers=None, query_params=None, post_params=None, body=None): + def PUT(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PUT", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) - def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None): + def PATCH(self, url, headers=None, query_params=None, post_params=None, body=None, _preload_content=True, + _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, body=body) diff --git a/samples/client/petstore-security-test/python/setup.py b/samples/client/petstore-security-test/python/setup.py index 21f9241b859..3f8f4c118e1 100644 --- a/samples/client/petstore-security-test/python/setup.py +++ b/samples/client/petstore-security-test/python/setup.py @@ -8,26 +8,14 @@ OpenAPI spec version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r Contact: apiteam@swagger.io */ ' \" =end -- \\r\\n \\n \\r Generated by: https://github.com/swagger-api/swagger-codegen.git - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. """ + import sys from setuptools import setup, find_packages NAME = "petstore_api" VERSION = "1.0.0" - # To install the library, run the following # # python setup.py install @@ -51,4 +39,3 @@ setup( This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end -- """ ) - diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 1c59d444ffc..fd16a182ca2 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -105,6 +105,7 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [EnumArrays](docs/EnumArrays.md) diff --git a/samples/client/petstore/python/docs/ClassModel.md b/samples/client/petstore/python/docs/ClassModel.md new file mode 100644 index 00000000000..7f6f6d17211 --- /dev/null +++ b/samples/client/petstore/python/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index 69186f43a50..cad45b8f219 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -153,7 +153,7 @@ enum_header_string_array = ['enum_header_string_array_example'] # list[str] | He enum_header_string = '-efg' # str | Header parameter enum test (string) (optional) (default to -efg) enum_query_string_array = ['enum_query_string_array_example'] # list[str] | Query parameter enum test (string array) (optional) enum_query_string = '-efg' # str | Query parameter enum test (string) (optional) (default to -efg) -enum_query_integer = 3.4 # float | Query parameter enum test (double) (optional) +enum_query_integer = 56 # int | Query parameter enum test (double) (optional) enum_query_double = 1.2 # float | Query parameter enum test (double) (optional) try: @@ -173,7 +173,7 @@ Name | Type | Description | Notes **enum_header_string** | **str**| Header parameter enum test (string) | [optional] [default to -efg] **enum_query_string_array** | [**list[str]**](str.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **str**| Query parameter enum test (string) | [optional] [default to -efg] - **enum_query_integer** | **float**| Query parameter enum test (double) | [optional] + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_double** | **float**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/python/petstore_api/__init__.py b/samples/client/petstore/python/petstore_api/__init__.py index 72c011b0f13..ad9f5a3e145 100644 --- a/samples/client/petstore/python/petstore_api/__init__.py +++ b/samples/client/petstore/python/petstore_api/__init__.py @@ -23,6 +23,7 @@ from .models.array_of_number_only import ArrayOfNumberOnly from .models.array_test import ArrayTest from .models.cat import Cat from .models.category import Category +from .models.class_model import ClassModel from .models.client import Client from .models.dog import Dog from .models.enum_arrays import EnumArrays diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index f5824c50572..d4a40cfcbfd 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -1,5 +1,4 @@ # coding: utf-8 - """ Swagger Petstore @@ -10,13 +9,8 @@ Generated by: https://github.com/swagger-api/swagger-codegen.git """ - from __future__ import absolute_import -from . import models -from .rest import RESTClientObject -from .rest import ApiException - import os import re import json @@ -24,14 +18,15 @@ import mimetypes import tempfile import threading -from datetime import datetime -from datetime import date +from datetime import date, datetime # python 2 and python 3 compatibility library from six import PY3, integer_types, iteritems, text_type from six.moves.urllib.parse import quote +from . import models from .configuration import Configuration +from .rest import ApiException, RESTClientObject class ApiClient(object): @@ -51,8 +46,20 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. """ - def __init__(self, host=None, header_name=None, header_value=None, cookie=None): + PRIMITIVE_TYPES = (float, bool, bytes, text_type) + integer_types + NATIVE_TYPES_MAPPING = { + 'int': int, + 'long': int if PY3 else long, + 'float': float, + 'str': str, + 'bool': bool, + 'date': date, + 'datetime': datetime, + 'object': object, + } + + def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ @@ -153,7 +160,10 @@ class ApiClient(object): return_data = None if callback: - callback(return_data) if _return_http_data_only else callback((return_data, response_data.status, response_data.getheaders())) + if _return_http_data_only: + callback(return_data) + else: + callback((return_data, response_data.status, response_data.getheaders())) elif _return_http_data_only: return (return_data) else: @@ -174,10 +184,9 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, float, bool, bytes) + tuple(integer_types) + (text_type,) - if isinstance(obj, type(None)): + if obj is None: return None - elif isinstance(obj, types): + elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) @@ -187,21 +196,21 @@ class ApiClient(object): for sub_obj in obj) elif isinstance(obj, (datetime, date)): return obj.isoformat() - else: - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} - return {key: self.sanitize_for_serialization(val) - for key, val in iteritems(obj_dict)} + if isinstance(obj, dict): + obj_dict = obj + else: + # Convert model obj to dict except + # attributes `swagger_types`, `attribute_map` + # and attributes which value is not None. + # Convert attribute name to json key in + # model definition for request. + obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) + for attr, _ in iteritems(obj.swagger_types) + if getattr(obj, attr) is not None} + + return {key: self.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ @@ -215,7 +224,7 @@ class ApiClient(object): """ # handle file downloading # save response body into a tmp file and return the instance - if "file" == response_type: + if response_type == "file": return self.__deserialize_file(response) # fetch data from response object @@ -250,17 +259,12 @@ class ApiClient(object): for k, v in iteritems(data)} # convert str to class - # for native types - if klass in ['int', 'float', 'str', 'bool', - "date", 'datetime', "object"]: - klass = eval(klass) - elif klass == 'long': - klass = int if PY3 else long - # for model types + if klass in self.NATIVE_TYPES_MAPPING: + klass = self.NATIVE_TYPES_MAPPING[klass] else: - klass = eval('models.' + klass) + klass = getattr(models, klass) - if klass in integer_types or klass in (float, str, bool): + if klass in self.PRIMITIVE_TYPES: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) @@ -460,7 +464,7 @@ class ApiClient(object): if not accepts: return - accepts = list(map(lambda x: x.lower(), accepts)) + accepts = [x.lower() for x in accepts] if 'application/json' in accepts: return 'application/json' @@ -477,7 +481,7 @@ class ApiClient(object): if not content_types: return 'application/json' - content_types = list(map(lambda x: x.lower(), content_types)) + content_types = [x.lower() for x in content_types] if 'application/json' in content_types or '*/*' in content_types: return 'application/json' @@ -547,12 +551,11 @@ class ApiClient(object): :return: int, long, float, str, bool. """ try: - value = klass(data) + return klass(data) except UnicodeEncodeError: - value = unicode(data) + return unicode(data) except TypeError: - value = data - return value + return data def __deserialize_object(self, value): """ @@ -577,8 +580,7 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a date object" - .format(string) + reason="Failed to parse `{0}` into a date object".format(string) ) def __deserialize_datatime(self, string): @@ -598,8 +600,10 @@ class ApiClient(object): except ValueError: raise ApiException( status=0, - reason="Failed to parse `{0}` into a datetime object". - format(string) + reason=( + "Failed to parse `{0}` into a datetime object" + .format(string) + ) ) def __deserialize_model(self, data, klass): @@ -617,7 +621,7 @@ class ApiClient(object): for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ - and instance.attribute_map[attr] in data\ + and instance.attribute_map[attr] in data \ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] setattr(instance, attr, self.__deserialize(value, attr_type)) diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 3da6777bb3a..31857574da7 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -258,14 +258,14 @@ class FakeApi(object): raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") if 'pattern_without_delimiter' in params and not re.search('^[A-Z].*', params['pattern_without_delimiter']): raise ValueError("Invalid value for parameter `pattern_without_delimiter` when calling `test_endpoint_parameters`, must conform to the pattern `/^[A-Z].*/`") - if 'integer' in params and params['integer'] > 100.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") - if 'integer' in params and params['integer'] < 10.0: - raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") - if 'int32' in params and params['int32'] > 200.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") - if 'int32' in params and params['int32'] < 20.0: - raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") + if 'integer' in params and params['integer'] > 100: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100`") + if 'integer' in params and params['integer'] < 10: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10`") + if 'int32' in params and params['int32'] > 200: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200`") + if 'int32' in params and params['int32'] < 20: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20`") if 'float' in params and params['float'] > 987.6: raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): @@ -364,7 +364,7 @@ class FakeApi(object): :param str enum_header_string: Header parameter enum test (string) :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) - :param float enum_query_integer: Query parameter enum test (double) + :param int enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) :return: None If the method is called asynchronously, @@ -396,7 +396,7 @@ class FakeApi(object): :param str enum_header_string: Header parameter enum test (string) :param list[str] enum_query_string_array: Query parameter enum test (string array) :param str enum_query_string: Query parameter enum test (string) - :param float enum_query_integer: Query parameter enum test (double) + :param int enum_query_integer: Query parameter enum test (double) :param float enum_query_double: Query parameter enum test (double) :return: None If the method is called asynchronously, diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index 82a4eee9e35..1764a9172b0 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -319,10 +319,10 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") - if 'order_id' in params and params['order_id'] > 5.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") - if 'order_id' in params and params['order_id'] < 1.0: - raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + if 'order_id' in params and params['order_id'] > 5: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5`") + if 'order_id' in params and params['order_id'] < 1: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1`") collection_formats = {} diff --git a/samples/client/petstore/python/petstore_api/models/__init__.py b/samples/client/petstore/python/petstore_api/models/__init__.py index e8a9a6a8d69..844bc150b72 100644 --- a/samples/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/client/petstore/python/petstore_api/models/__init__.py @@ -23,6 +23,7 @@ from .array_of_number_only import ArrayOfNumberOnly from .array_test import ArrayTest from .cat import Cat from .category import Category +from .class_model import ClassModel from .client import Client from .dog import Dog from .enum_arrays import EnumArrays diff --git a/samples/client/petstore/python/petstore_api/models/class_model.py b/samples/client/petstore/python/petstore_api/models/class_model.py new file mode 100644 index 00000000000..dd08406c04b --- /dev/null +++ b/samples/client/petstore/python/petstore_api/models/class_model.py @@ -0,0 +1,112 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from pprint import pformat +from six import iteritems +import re + + +class ClassModel(object): + """ + NOTE: This class is auto generated by the swagger code generator program. + Do not edit the class manually. + """ + def __init__(self, _class=None): + """ + ClassModel - a model defined in Swagger + + :param dict swaggerTypes: The key is attribute name + and the value is attribute type. + :param dict attributeMap: The key is attribute name + and the value is json key in definition. + """ + self.swagger_types = { + '_class': 'str' + } + + self.attribute_map = { + '_class': '_class' + } + + self.__class = _class + + @property + def _class(self): + """ + Gets the _class of this ClassModel. + + :return: The _class of this ClassModel. + :rtype: str + """ + return self.__class + + @_class.setter + def _class(self, _class): + """ + Sets the _class of this ClassModel. + + :param _class: The _class of this ClassModel. + :type: str + """ + + self.__class = _class + + def to_dict(self): + """ + Returns the model properties as a dict + """ + result = {} + + for attr, _ in iteritems(self.swagger_types): + value = getattr(self, attr) + if isinstance(value, list): + result[attr] = list(map( + lambda x: x.to_dict() if hasattr(x, "to_dict") else x, + value + )) + elif hasattr(value, "to_dict"): + result[attr] = value.to_dict() + elif isinstance(value, dict): + result[attr] = dict(map( + lambda item: (item[0], item[1].to_dict()) + if hasattr(item[1], "to_dict") else item, + value.items() + )) + else: + result[attr] = value + + return result + + def to_str(self): + """ + Returns the string representation of the model + """ + return pformat(self.to_dict()) + + def __repr__(self): + """ + For `print` and `pprint` + """ + return self.to_str() + + def __eq__(self, other): + """ + Returns true if both objects are equal + """ + return self.__dict__ == other.__dict__ + + def __ne__(self, other): + """ + Returns true if both objects are not equal + """ + return not self == other diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index dcefc1e036b..1223bb1ea99 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -94,10 +94,10 @@ class FormatTest(object): :param integer: The integer of this FormatTest. :type: int """ - if integer is not None and integer > 100.0: - raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") - if integer is not None and integer < 10.0: - raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") + if integer is not None and integer > 100: + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100`") + if integer is not None and integer < 10: + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10`") self._integer = integer @@ -119,10 +119,10 @@ class FormatTest(object): :param int32: The int32 of this FormatTest. :type: int """ - if int32 is not None and int32 > 200.0: - raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") - if int32 is not None and int32 < 20.0: - raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") + if int32 is not None and int32 > 200: + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200`") + if int32 is not None and int32 < 20: + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20`") self._int32 = int32 diff --git a/samples/client/petstore/python/test/test_class_model.py b/samples/client/petstore/python/test/test_class_model.py new file mode 100644 index 00000000000..e502152ee8b --- /dev/null +++ b/samples/client/petstore/python/test/test_class_model.py @@ -0,0 +1,42 @@ +# coding: utf-8 + +""" + Swagger Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +""" + + +from __future__ import absolute_import + +import os +import sys +import unittest + +import petstore_api +from petstore_api.rest import ApiException +from petstore_api.models.class_model import ClassModel + + +class TestClassModel(unittest.TestCase): + """ ClassModel unit test stubs """ + + def setUp(self): + pass + + def tearDown(self): + pass + + def testClassModel(self): + """ + Test ClassModel + """ + model = petstore_api.models.class_model.ClassModel() + + +if __name__ == '__main__': + unittest.main() From 7a97c3c37554a4a2cd7919e8ef0ff83d192f0bdf Mon Sep 17 00:00:00 2001 From: Thomas Hoffmann Date: Fri, 9 Dec 2016 10:27:55 +0100 Subject: [PATCH 146/269] Still respect super.equals even for models without own vars (#4259) --- modules/swagger-codegen/src/main/resources/Java/pojo.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index a76452fddc8..6a26e7516dc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -96,7 +96,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#parcela return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{#hasMore}} && {{/hasMore}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} - return true;{{/hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} } @Override From 6e578f437f51ceed46519a60f4551eff68fafd8c Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 9 Dec 2016 23:21:45 +0800 Subject: [PATCH 147/269] add keyword (sdk generation) --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 95e0bb1e6d8..1280b9f9d6f 100644 --- a/README.md +++ b/README.md @@ -13,9 +13,9 @@ :warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning: ## Overview -This is the swagger codegen project, which allows generation of API client libraries, server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). +This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). -Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the Swagger project, including additional libraries with support for other languages and more. +Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project. # Table of contents From c83c813865a75f8fb9ead947e9b2c16ce69e3cb6 Mon Sep 17 00:00:00 2001 From: Sreenidhi Sreesha Date: Fri, 9 Dec 2016 08:37:50 -0800 Subject: [PATCH 148/269] Refactor Boolean properties to boolean. (#4326) There is no good reason to use Boolean instead of boolean. Using Boolean will lead to handling "null" state which is confusing. This change removes changes the type of Boolean properties to boolean. --- .../java/io/swagger/codegen/CodegenModel.java | 24 ++-- .../io/swagger/codegen/CodegenOperation.java | 62 +++++----- .../io/swagger/codegen/CodegenProperty.java | 108 +++++++++--------- .../io/swagger/codegen/DefaultCodegen.java | 59 +++++----- .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../languages/AbstractJavaCodegen.java | 2 +- .../languages/FlaskConnexionCodegen.java | 2 +- .../languages/JavascriptClientCodegen.java | 6 +- .../languages/NodeJSServerCodegen.java | 2 +- .../codegen/languages/Swift3Codegen.java | 2 +- .../codegen/csharp/CSharpModelTest.java | 24 ++-- .../io/swagger/codegen/go/GoModelTest.java | 18 +-- .../swagger/codegen/java/JavaModelTest.java | 32 +++--- .../javascript/JavaScriptModelEnumTest.java | 2 +- .../javascript/JavaScriptModelTest.java | 30 ++--- .../swagger/codegen/objc/ObjcModelTest.java | 22 ++-- .../io/swagger/codegen/php/PhpModelTest.java | 20 ++-- .../io/swagger/codegen/python/PythonTest.java | 18 +-- .../swagger/codegen/scala/ScalaModelTest.java | 16 +-- .../swagger/codegen/swift/SwiftModelTest.java | 10 +- .../codegen/swift3/Swift3ModelTest.java | 10 +- .../fetch/TypeScriptFetchModelTest.java | 14 +-- .../TypeScriptAngularModelTest.java | 12 +- .../TypeScriptAngular2ModelTest.java | 12 +- .../TypeScriptNodeModelTest.java | 12 +- 25 files changed, 260 insertions(+), 261 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 6b0dd68e9fb..7f89ef738a0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -39,8 +39,8 @@ public class CodegenModel { public Set allMandatory; public Set imports = new TreeSet(); - public Boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren; - public Boolean hasOnlyReadOnly = true; // true if all properties are read-only + public boolean hasVars, emptyVars, hasMoreModels, hasEnums, isEnum, hasRequired, isArrayModel, hasChildren; + public boolean hasOnlyReadOnly = true; // true if all properties are read-only public ExternalDocs externalDocs; public Map vendorExtensions; @@ -115,15 +115,15 @@ public class CodegenModel { return false; if (imports != null ? !imports.equals(that.imports) : that.imports != null) return false; - if (hasVars != null ? !hasVars.equals(that.hasVars) : that.hasVars != null) + if (hasVars != that.hasVars) return false; - if (emptyVars != null ? !emptyVars.equals(that.emptyVars) : that.emptyVars != null) + if (emptyVars != that.emptyVars) return false; - if (hasMoreModels != null ? !hasMoreModels.equals(that.hasMoreModels) : that.hasMoreModels != null) + if (hasMoreModels != that.hasMoreModels) return false; - if (hasEnums != null ? !hasEnums.equals(that.hasEnums) : that.hasEnums != null) + if (hasEnums != that.hasEnums) return false; - if (isEnum != null ? !isEnum.equals(that.isEnum) : that.isEnum != null) + if (isEnum != that.isEnum) return false; if (externalDocs != null ? !externalDocs.equals(that.externalDocs) : that.externalDocs != null) return false; @@ -163,11 +163,11 @@ public class CodegenModel { result = 31 * result + (mandatory != null ? mandatory.hashCode() : 0); result = 31 * result + (allMandatory != null ? allMandatory.hashCode() : 0); result = 31 * result + (imports != null ? imports.hashCode() : 0); - result = 31 * result + (hasVars != null ? hasVars.hashCode() : 0); - result = 31 * result + (emptyVars != null ? emptyVars.hashCode() : 0); - result = 31 * result + (hasMoreModels != null ? hasMoreModels.hashCode() : 0); - result = 31 * result + (hasEnums != null ? hasEnums.hashCode() : 0); - result = 31 * result + (isEnum != null ? isEnum.hashCode() : 0); + result = 31 * result + (hasVars ? 13:31); + result = 31 * result + (emptyVars ? 13:31); + result = 31 * result + (hasMoreModels ? 13:31); + result = 31 * result + (hasEnums ? 13:31); + result = 31 * result + (isEnum ? 13:31); result = 31 * result + (externalDocs != null ? externalDocs.hashCode() : 0); result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); result = 31 * result + Objects.hash(hasOnlyReadOnly); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 1bd02c68d5d..940a6b74cc3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -11,10 +11,10 @@ import java.util.Arrays; public class CodegenOperation { public final List responseHeaders = new ArrayList(); - public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, + public boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, hasOptionalParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, - isListContainer, isMultipart, hasMore = Boolean.TRUE, - isResponseBinary = Boolean.FALSE, hasReference = Boolean.FALSE, + isListContainer, isMultipart, hasMore = true, + isResponseBinary = false, hasReference = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, isRestful; public String path, operationId, returnType, httpMethod, returnBaseType, @@ -189,33 +189,33 @@ public class CodegenOperation { if (responseHeaders != null ? !responseHeaders.equals(that.responseHeaders) : that.responseHeaders != null) return false; - if (hasAuthMethods != null ? !hasAuthMethods.equals(that.hasAuthMethods) : that.hasAuthMethods != null) + if (hasAuthMethods != that.hasAuthMethods) return false; - if (hasConsumes != null ? !hasConsumes.equals(that.hasConsumes) : that.hasConsumes != null) + if (hasConsumes != that.hasConsumes) return false; - if (hasProduces != null ? !hasProduces.equals(that.hasProduces) : that.hasProduces != null) + if (hasProduces != that.hasProduces) return false; - if (hasParams != null ? !hasParams.equals(that.hasParams) : that.hasParams != null) + if (hasParams != that.hasParams) return false; - if (hasOptionalParams != null ? !hasOptionalParams.equals(that.hasOptionalParams) : that.hasOptionalParams != null) + if (hasOptionalParams != that.hasOptionalParams) return false; - if (returnTypeIsPrimitive != null ? !returnTypeIsPrimitive.equals(that.returnTypeIsPrimitive) : that.returnTypeIsPrimitive != null) + if (returnTypeIsPrimitive != that.returnTypeIsPrimitive) return false; - if (returnSimpleType != null ? !returnSimpleType.equals(that.returnSimpleType) : that.returnSimpleType != null) + if (returnSimpleType != that.returnSimpleType) return false; - if (subresourceOperation != null ? !subresourceOperation.equals(that.subresourceOperation) : that.subresourceOperation != null) + if (subresourceOperation != that.subresourceOperation) return false; - if (isMapContainer != null ? !isMapContainer.equals(that.isMapContainer) : that.isMapContainer != null) + if (isMapContainer != that.isMapContainer) return false; - if (isListContainer != null ? !isListContainer.equals(that.isListContainer) : that.isListContainer != null) + if (isListContainer != that.isListContainer) return false; - if (isMultipart != null ? !isMultipart.equals(that.isMultipart) : that.isMultipart != null) + if (isMultipart != that.isMultipart) return false; - if (hasMore != null ? !hasMore.equals(that.hasMore) : that.hasMore != null) + if (hasMore != that.hasMore) return false; - if (isResponseBinary != null ? !isResponseBinary.equals(that.isResponseBinary) : that.isResponseBinary != null) + if (isResponseBinary != that.isResponseBinary) return false; - if (hasReference != null ? !hasReference.equals(that.hasReference) : that.hasReference != null) + if (hasReference != that.hasReference) return false; if (path != null ? !path.equals(that.path) : that.path != null) return false; @@ -284,20 +284,20 @@ public class CodegenOperation { @Override public int hashCode() { int result = responseHeaders.hashCode(); - result = 31 * result + (hasAuthMethods != null ? hasAuthMethods.hashCode() : 0); - result = 31 * result + (hasConsumes != null ? hasConsumes.hashCode() : 0); - result = 31 * result + (hasProduces != null ? hasProduces.hashCode() : 0); - result = 31 * result + (hasParams != null ? hasParams.hashCode() : 0); - result = 31 * result + (hasOptionalParams != null ? hasOptionalParams.hashCode() : 0); - result = 31 * result + (returnTypeIsPrimitive != null ? returnTypeIsPrimitive.hashCode() : 0); - result = 31 * result + (returnSimpleType != null ? returnSimpleType.hashCode() : 0); - result = 31 * result + (subresourceOperation != null ? subresourceOperation.hashCode() : 0); - result = 31 * result + (isMapContainer != null ? isMapContainer.hashCode() : 0); - result = 31 * result + (isListContainer != null ? isListContainer.hashCode() : 0); - result = 31 * result + (isMultipart != null ? isMultipart.hashCode() : 0); - result = 31 * result + (hasMore != null ? hasMore.hashCode() : 0); - result = 31 * result + (isResponseBinary != null ? isResponseBinary.hashCode() : 0); - result = 31 * result + (hasReference != null ? hasReference.hashCode() : 0); + result = 31 * result + (hasAuthMethods ? 13:31); + result = 31 * result + (hasConsumes ? 13:31); + result = 31 * result + (hasProduces ? 13:31); + result = 31 * result + (hasParams ? 13:31); + result = 31 * result + (hasOptionalParams ? 13:31); + result = 31 * result + (returnTypeIsPrimitive ? 13:31); + result = 31 * result + (returnSimpleType ? 13:31); + result = 31 * result + (subresourceOperation ? 13:31); + result = 31 * result + (isMapContainer ? 13:31); + result = 31 * result + (isListContainer ? 13:31); + result = 31 * result + (isMultipart ? 13:31); + result = 31 * result + (hasMore ? 13:31); + result = 31 * result + (isResponseBinary ? 13:31); + result = 31 * result + (hasReference ? 13:31); result = 31 * result + (path != null ? path.hashCode() : 0); result = 31 * result + (operationId != null ? operationId.hashCode() : 0); result = 31 * result + (returnType != null ? returnType.hashCode() : 0); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index e4238b5cae6..834ab9d5ea4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -32,21 +32,21 @@ public class CodegenProperty implements Cloneable { public String jsonSchema; public String minimum; public String maximum; - public Boolean exclusiveMinimum; - public Boolean exclusiveMaximum; - public Boolean hasMore, required, secondaryParam; - public Boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly - public Boolean isPrimitiveType, isContainer, isNotContainer; - public Boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; - public Boolean isListContainer, isMapContainer; + public boolean exclusiveMinimum; + public boolean exclusiveMaximum; + public boolean hasMore, required, secondaryParam; + public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly + public boolean isPrimitiveType, isContainer, isNotContainer; + public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime; + public boolean isListContainer, isMapContainer; public boolean isEnum; - public Boolean isReadOnly = false; + public boolean isReadOnly = false; public List _enum; public Map allowableValues; public CodegenProperty items; public Map vendorExtensions; - public Boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template) - public Boolean isInherited; + public boolean hasValidation; // true if pattern, maximum, etc are set (only used in the mustache template) + public boolean isInherited; public String nameInCamelCase; // property name in camel case // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1) public String enumName; @@ -75,16 +75,16 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((example == null) ? 0 : example.hashCode()); - result = prime * result + ((exclusiveMaximum == null) ? 0 : exclusiveMaximum.hashCode()); - result = prime * result + ((exclusiveMinimum == null) ? 0 : exclusiveMinimum.hashCode()); + result = prime * result + (exclusiveMaximum ? 13:31); + result = prime * result + (exclusiveMinimum ? 13:31); result = prime * result + ((getter == null) ? 0 : getter.hashCode()); - result = prime * result + ((hasMore == null) ? 0 : hasMore.hashCode()); - result = prime * result + ((hasMoreNonReadOnly == null) ? 0 : hasMoreNonReadOnly.hashCode()); - result = prime * result + ((isContainer == null) ? 0 : isContainer.hashCode()); + result = prime * result + (hasMore ? 13:31); + result = prime * result + ((hasMoreNonReadOnly ? 13:31)); + result = prime * result + ((isContainer ? 13:31)); result = prime * result + (isEnum ? 1231 : 1237); - result = prime * result + ((isNotContainer == null) ? 0 : isNotContainer.hashCode()); - result = prime * result + ((isPrimitiveType == null) ? 0 : isPrimitiveType.hashCode()); - result = prime * result + ((isReadOnly == null) ? 0 : isReadOnly.hashCode()); + result = prime * result + ((isNotContainer ? 13:31)); + result = prime * result + ((isPrimitiveType ? 13:31)); + result = prime * result + ((isReadOnly ? 13:31)); result = prime * result + ((items == null) ? 0 : items.hashCode()); result = prime * result + ((jsonSchema == null) ? 0 : jsonSchema.hashCode()); result = prime * result + ((max == null) ? 0 : max.hashCode()); @@ -95,24 +95,24 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((minimum == null) ? 0 : minimum.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); - result = prime * result + ((required == null) ? 0 : required.hashCode()); - result = prime * result + ((secondaryParam == null) ? 0 : secondaryParam.hashCode()); + result = prime * result + ((required ? 13:31)); + result = prime * result + ((secondaryParam ? 13:31)); result = prime * result + ((setter == null) ? 0 : setter.hashCode()); result = prime * result + ((unescapedDescription == null) ? 0 : unescapedDescription.hashCode()); result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode()); - result = prime * result + ((hasValidation == null) ? 0 : hasValidation.hashCode()); - result = prime * result + ((isString == null) ? 0 : isString.hashCode()); - result = prime * result + ((isInteger == null) ? 0 : isInteger.hashCode()); - result = prime * result + ((isLong == null) ? 0 : isLong.hashCode()); - result = prime * result + ((isFloat == null) ? 0 : isFloat.hashCode()); - result = prime * result + ((isDouble == null) ? 0 : isDouble.hashCode()); - result = prime * result + ((isByteArray == null) ? 0 : isByteArray.hashCode()); - result = prime * result + ((isBinary == null) ? 0 : isBinary.hashCode()); - result = prime * result + ((isBoolean == null) ? 0 : isBoolean.hashCode()); - result = prime * result + ((isDate == null) ? 0 : isDate.hashCode()); - result = prime * result + ((isDateTime == null) ? 0 : isDateTime.hashCode()); - result = prime * result + ((isMapContainer == null) ? 0 : isMapContainer.hashCode()); - result = prime * result + ((isListContainer == null) ? 0 : isListContainer.hashCode()); + result = prime * result + ((hasValidation ? 13:31)); + result = prime * result + ((isString ? 13:31)); + result = prime * result + ((isInteger ? 13:31)); + result = prime * result + ((isLong ?13:31)); + result = prime * result + ((isFloat ? 13:31)); + result = prime * result + ((isDouble ? 13:31)); + result = prime * result + ((isByteArray ? 13:31)); + result = prime * result + ((isBinary ? 13:31)); + result = prime * result + ((isBoolean ? 13:31)); + result = prime * result + ((isDate ? 13:31)); + result = prime * result + ((isDateTime ? 13:31)); + result = prime * result + ((isMapContainer ? 13:31)); + result = prime * result + ((isListContainer ? 13:31)); result = prime * result + Objects.hashCode(isInherited); result = prime * result + Objects.hashCode(nameInCamelCase); result = prime * result + Objects.hashCode(enumName); @@ -191,31 +191,31 @@ public class CodegenProperty implements Cloneable { if (this.maximum != other.maximum && (this.maximum == null || !this.maximum.equals(other.maximum))) { return false; } - if (this.exclusiveMinimum != other.exclusiveMinimum && (this.exclusiveMinimum == null || !this.exclusiveMinimum.equals(other.exclusiveMinimum))) { + if (this.exclusiveMinimum != other.exclusiveMinimum) { return false; } - if (this.exclusiveMaximum != other.exclusiveMaximum && (this.exclusiveMaximum == null || !this.exclusiveMaximum.equals(other.exclusiveMaximum))) { + if (this.exclusiveMaximum != other.exclusiveMaximum) { return false; } - if (this.required != other.required && (this.required == null || !this.required.equals(other.required))) { + if (this.required != other.required) { return false; } - if (this.secondaryParam != other.secondaryParam && (this.secondaryParam == null || !this.secondaryParam.equals(other.secondaryParam))) { + if (this.secondaryParam != other.secondaryParam) { return false; } - if (this.isPrimitiveType != other.isPrimitiveType && (this.isPrimitiveType == null || !this.isPrimitiveType.equals(other.isPrimitiveType))) { + if (this.isPrimitiveType != other.isPrimitiveType) { return false; } - if (this.isContainer != other.isContainer && (this.isContainer == null || !this.isContainer.equals(other.isContainer))) { + if (this.isContainer != other.isContainer) { return false; } - if (this.isNotContainer != other.isNotContainer && (this.isNotContainer == null || !this.isNotContainer.equals(other.isNotContainer))) { + if (this.isNotContainer != other.isNotContainer) { return false; } if (this.isEnum != other.isEnum) { return false; } - if (this.isReadOnly != other.isReadOnly && (this.isReadOnly == null || !this.isReadOnly.equals(other.isReadOnly))) { + if (this.isReadOnly != other.isReadOnly) { return false; } if (this._enum != other._enum && (this._enum == null || !this._enum.equals(other._enum))) { @@ -229,45 +229,45 @@ public class CodegenProperty implements Cloneable { return false; } - if (this.hasValidation != other.hasValidation && (this.hasValidation == null || !this.hasValidation.equals(other.hasValidation))) { + if (this.hasValidation != other.hasValidation) { return false; } - if (this.isString != other.isString && (this.isString == null || !this.isString.equals(other.isString))) { + if (this.isString != other.isString) { return false; } - if (this.isInteger != other.isInteger && (this.isInteger == null || !this.isInteger.equals(other.isInteger))) { + if (this.isInteger != other.isInteger) { return false; } - if (this.isLong != other.isLong && (this.isLong == null || !this.isLong.equals(other.isLong))) { + if (this.isLong != other.isLong) { return false; } - if (this.isFloat != other.isFloat && (this.isFloat == null || !this.isFloat.equals(other.isFloat))) { + if (this.isFloat != other.isFloat) { return false; } - if (this.isDouble != other.isDouble && (this.isDouble == null || !this.isDouble.equals(other.isDouble))) { + if (this.isDouble != other.isDouble) { return false; } - if (this.isByteArray != other.isByteArray && (this.isByteArray == null || !this.isByteArray.equals(other.isByteArray))) { + if (this.isByteArray != other.isByteArray) { return false; } - if (this.isBoolean != other.isBoolean && (this.isBoolean == null || !this.isBoolean.equals(other.isBoolean))) { + if (this.isBoolean != other.isBoolean) { return false; } - if (this.isDate != other.isDate && (this.isDate == null || !this.isDate.equals(other.isDate))) { + if (this.isDate != other.isDate) { return false; } - if (this.isDateTime != other.isDateTime && (this.isDateTime == null || !this.isDateTime.equals(other.isDateTime))) { + if (this.isDateTime != other.isDateTime) { return false; } - if (this.isBinary != other.isBinary && (this.isBinary == null || !this.isBinary.equals(other.isBinary))) { + if (this.isBinary != other.isBinary) { return false; } - if (this.isListContainer != other.isListContainer && (this.isListContainer == null || !this.isListContainer.equals(other.isListContainer))) { + if (this.isListContainer != other.isListContainer) { return false; } - if (this.isMapContainer != other.isMapContainer && (this.isMapContainer == null || !this.isMapContainer.equals(other.isMapContainer))) { + if (this.isMapContainer != other.isMapContainer) { return false; } if (!Objects.equals(this.isInherited, other.isInherited)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 5a4c69ff291..ce716c1bb02 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1241,7 +1241,6 @@ public class DefaultCodegen { if (model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); - m.hasEnums = false; // Otherwise there will be a NullPointerException in JavaClientCodegen.fromModel m.isArrayModel = true; m.arrayModelType = fromProperty(name, arrayProperty).complexType; addParentContainer(m, name, arrayProperty); @@ -1438,36 +1437,35 @@ public class DefaultCodegen { property.defaultValue = toDefaultValue(p); property.defaultValueWithParam = toDefaultValueWithParam(name, p); property.jsonSchema = Json.pretty(p); - property.isReadOnly = p.getReadOnly(); + if (p.getReadOnly() != null) { + property.isReadOnly = p.getReadOnly(); + } property.vendorExtensions = p.getVendorExtensions(); String type = getSwaggerType(p); if (p instanceof AbstractNumericProperty) { AbstractNumericProperty np = (AbstractNumericProperty) p; if (np.getMinimum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.minimum = String.valueOf(np.getMinimum().longValue()); - } else { // double, decimal - property.minimum = String.valueOf(np.getMinimum()); - } - } else { - // set to null (empty) in mustache - property.minimum = null; + if (p instanceof BaseIntegerProperty) { // int, long + property.minimum = String.valueOf(np.getMinimum().longValue()); + } else { // double, decimal + property.minimum = String.valueOf(np.getMinimum()); + } } - if (np.getMaximum() != null) { - if (p instanceof BaseIntegerProperty) { // int, long - property.maximum = String.valueOf(np.getMaximum().longValue()); - } else { // double, decimal - property.maximum = String.valueOf(np.getMaximum()); - } - } else { - // set to null (empty) in mustache - property.maximum = null; + if (p instanceof BaseIntegerProperty) { // int, long + property.maximum = String.valueOf(np.getMaximum().longValue()); + } else { // double, decimal + property.maximum = String.valueOf(np.getMaximum()); + } } - property.exclusiveMinimum = np.getExclusiveMinimum(); - property.exclusiveMaximum = np.getExclusiveMaximum(); + if (np.getExclusiveMinimum() != null) { + property.exclusiveMinimum = np.getExclusiveMinimum(); + } + if (np.getExclusiveMaximum() != null) { + property.exclusiveMaximum = np.getExclusiveMaximum(); + } // check if any validation rule defined // exclusive* are noop without corresponding min/max @@ -2030,14 +2028,14 @@ public class DefaultCodegen { } } - if (cm.isContainer != null) { + if (cm.isContainer) { op.returnContainer = cm.containerType; if ("map".equals(cm.containerType)) { - op.isMapContainer = Boolean.TRUE; + op.isMapContainer = true; } else if ("list".equalsIgnoreCase(cm.containerType)) { - op.isListContainer = Boolean.TRUE; + op.isListContainer = true; } else if ("array".equalsIgnoreCase(cm.containerType)) { - op.isListContainer = Boolean.TRUE; + op.isListContainer = true; } } else { op.returnSimpleType = true; @@ -2195,7 +2193,7 @@ public class DefaultCodegen { } r.dataType = cm.datatype; r.isBinary = isDataTypeBinary(cm.datatype); - if (cm.isContainer != null) { + if (cm.isContainer) { r.simpleType = false; r.containerType = cm.containerType; r.isMapContainer = "map".equals(cm.containerType); @@ -2342,6 +2340,7 @@ public class DefaultCodegen { p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum()); p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum()); } + p.exclusiveMaximum = qp.isExclusiveMaximum(); p.exclusiveMinimum = qp.isExclusiveMinimum(); p.maxLength = qp.getMaxLength(); @@ -2371,7 +2370,7 @@ public class DefaultCodegen { if (model instanceof ModelImpl) { ModelImpl impl = (ModelImpl) model; CodegenModel cm = fromModel(bp.getName(), impl); - if (cm.emptyVars != null && cm.emptyVars == false) { + if (!cm.emptyVars) { p.dataType = getTypeDeclaration(cm.classname); imports.add(p.dataType); } else { @@ -2848,8 +2847,8 @@ public class DefaultCodegen { LOGGER.warn("null property for " + key); } else { final CodegenProperty cp = fromProperty(key, prop); - cp.required = mandatory.contains(key) ? true : null; - m.hasRequired = Boolean.TRUE.equals(m.hasRequired) || Boolean.TRUE.equals(cp.required); + cp.required = mandatory.contains(key) ? true : false; + m.hasRequired = m.hasRequired || cp.required; if (cp.isEnum) { // FIXME: if supporting inheritance, when called a second time for allProperties it is possible for // m.hasEnums to be set incorrectly if allProperties has enumerations but properties does not. @@ -2869,7 +2868,7 @@ public class DefaultCodegen { } } - if (cp.isContainer != null) { + if (cp.isContainer) { addImport(m, typeMapping.get("array")); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index e3aee70a1b2..667b6342b9b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -870,7 +870,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (os != null && os.size() > 0) { CodegenOperation op = os.get(os.size() - 1); - op.hasMore = null; + op.hasMore = false; } } return operations; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 829e2604f1d..2fb928e4c49 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -863,7 +863,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code int count = 0, numVars = codegenProperties.size(); for(CodegenProperty codegenProperty : codegenProperties) { count += 1; - codegenProperty.hasMore = (count < numVars) ? true : null; + codegenProperty.hasMore = (count < numVars) ? true : false; } codegenModel.vars = codegenProperties; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index 0f58aecc262..e0c7218b723 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -345,7 +345,7 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf opsByPathEntry.put("path", entry.getKey()); opsByPathEntry.put("operation", entry.getValue()); List operationsForThisPath = Lists.newArrayList(entry.getValue()); - operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null; + operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false; if (opsByPathList.size() < opsByPath.asMap().size()) { opsByPathEntry.put("hasMore", "true"); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 76ef0d38c90..8a1ff5ce1d2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -927,14 +927,14 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo // set vendor-extension: x-codegen-hasMoreRequired CodegenProperty lastRequired = null; for (CodegenProperty var : cm.vars) { - if (var.required != null && var.required) { + if (var.required) { lastRequired = var; } } for (CodegenProperty var : cm.vars) { if (var == lastRequired) { var.vendorExtensions.put("x-codegen-hasMoreRequired", false); - } else if (var.required != null && var.required) { + } else if (var.required) { var.vendorExtensions.put("x-codegen-hasMoreRequired", true); } } @@ -996,7 +996,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo int count = 0, numVars = codegenProperties.size(); for(CodegenProperty codegenProperty : codegenProperties) { count += 1; - codegenProperty.hasMore = (count < numVars) ? true : null; + codegenProperty.hasMore = (count < numVars) ? true : false; } codegenModel.vars = codegenProperties; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 184027dd42b..b9ab1b00f8b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -231,7 +231,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig opsByPathEntry.put("path", entry.getKey()); opsByPathEntry.put("operation", entry.getValue()); List operationsForThisPath = Lists.newArrayList(entry.getValue()); - operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = null; + operationsForThisPath.get(operationsForThisPath.size() - 1).hasMore = false; if (opsByPathList.size() < opsByPath.asMap().size()) { opsByPathEntry.put("hasMore", "true"); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 95dd23e0e15..8810b2790c6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -621,7 +621,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { int count = 0, numVars = codegenProperties.size(); for(CodegenProperty codegenProperty : codegenProperties) { count += 1; - codegenProperty.hasMore = (count < numVars) ? true : null; + codegenProperty.hasMore = (count < numVars) ? true : false; } codegenModel.vars = codegenProperties; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java index 236bd44e32b..6e5c2076f5d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpModelTest.java @@ -47,7 +47,7 @@ public class CSharpModelTest { Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "List"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -70,7 +70,7 @@ public class CSharpModelTest { Assert.assertEquals(property.datatype, "Collection"); Assert.assertEquals(property.baseType, "Collection"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -96,7 +96,7 @@ public class CSharpModelTest { Assert.assertEquals(property.baseType, "Collection", "returnICollection option should not modify property baseType"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -153,8 +153,8 @@ public class CSharpModelTest { Assert.assertEquals(property3.name, "CreatedAt"); Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "DateTime?"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -191,9 +191,9 @@ public class CSharpModelTest { Assert.assertEquals(property2.name, "Urls"); Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "List"); - Assert.assertNull(property2.hasMore); + Assert.assertFalse(property2.hasMore); Assert.assertEquals(property2.containerType, "array"); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isPrimitiveType); Assert.assertTrue(property2.isContainer); } @@ -219,7 +219,7 @@ public class CSharpModelTest { Assert.assertEquals(property1.name, "Translations"); Assert.assertEquals(property1.baseType, "Dictionary"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); Assert.assertTrue(property1.isPrimitiveType); } @@ -242,7 +242,7 @@ public class CSharpModelTest { Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -267,7 +267,7 @@ public class CSharpModelTest { Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "List"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -293,9 +293,9 @@ public class CSharpModelTest { Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "Dictionary"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } @Test(description = "convert an array model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java index ce9646398f0..e631b259445 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/go/GoModelTest.java @@ -69,8 +69,8 @@ public class GoModelTest { Assert.assertEquals(property3.name, "CreatedAt"); Assert.assertEquals(property3.defaultValue, "null"); Assert.assertEquals(property3.baseType, "time.Time"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -106,9 +106,9 @@ public class GoModelTest { Assert.assertEquals(property2.datatype, "[]string"); Assert.assertEquals(property2.name, "Urls"); Assert.assertEquals(property2.baseType, "array"); - Assert.assertNull(property2.hasMore); + Assert.assertFalse(property2.hasMore); Assert.assertEquals(property2.containerType, "array"); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isPrimitiveType); Assert.assertTrue(property2.isContainer); } @@ -134,7 +134,7 @@ public class GoModelTest { Assert.assertEquals(property1.name, "Translations"); Assert.assertEquals(property1.baseType, "map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); Assert.assertTrue(property1.isPrimitiveType); } @@ -157,7 +157,7 @@ public class GoModelTest { Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -181,7 +181,7 @@ public class GoModelTest { Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "array"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -207,9 +207,9 @@ public class GoModelTest { Assert.assertEquals(property1.name, "Children"); Assert.assertEquals(property1.baseType, "map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } @Test(description = "convert an array model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 82d1555ea78..7dfd05faca7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -81,8 +81,8 @@ public class JavaModelTest { Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); Assert.assertEquals(property3.baseType, "Date"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -111,7 +111,7 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new ArrayList()"); Assert.assertEquals(property.baseType, "List"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -139,7 +139,7 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new HashMap()"); Assert.assertEquals(property.baseType, "Map"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -167,7 +167,7 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new HashMap>()"); Assert.assertEquals(property.baseType, "Map"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -189,7 +189,7 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new ArrayList>()"); Assert.assertEquals(property.baseType, "List"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -213,7 +213,7 @@ public class JavaModelTest { Assert.assertEquals(property.name, "children"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "Children"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isNotContainer); } @@ -240,7 +240,7 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new ArrayList()"); Assert.assertEquals(property.baseType, "List"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -268,9 +268,9 @@ public class JavaModelTest { Assert.assertEquals(property.defaultValue, "new HashMap()"); Assert.assertEquals(property.baseType, "Map"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); - Assert.assertNull(property.isNotContainer); + Assert.assertFalse(property.isNotContainer); } @@ -329,7 +329,7 @@ public class JavaModelTest { Assert.assertEquals(property.name, "NAME"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.required); Assert.assertTrue(property.isNotContainer); } @@ -355,7 +355,7 @@ public class JavaModelTest { Assert.assertEquals(property.name, "pId"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.required); Assert.assertTrue(property.isNotContainer); } @@ -381,7 +381,7 @@ public class JavaModelTest { Assert.assertEquals(property.name, "atTName"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.required); Assert.assertTrue(property.isNotContainer); } @@ -443,8 +443,8 @@ public class JavaModelTest { Assert.assertEquals(property.name, "inputBinaryData"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "byte[]"); - Assert.assertNull(property.hasMore); - Assert.assertNull(property.required); + Assert.assertFalse(property.hasMore); + Assert.assertFalse(property.required); Assert.assertTrue(property.isNotContainer); } @@ -468,7 +468,7 @@ public class JavaModelTest { Assert.assertEquals(property.name, "u"); Assert.assertEquals(property.defaultValue, "null"); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.isNotContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java index 4ef973b7df7..0aedbdf89e0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -137,7 +137,7 @@ public class JavaScriptModelEnumTest { Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); Assert.assertTrue(prope.isEnum); - Assert.assertNull(prope.isContainer); + Assert.assertFalse(prope.isContainer); Assert.assertNull(prope.items); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java index c396ec26f1c..b159918c73c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelTest.java @@ -81,8 +81,8 @@ public class JavaScriptModelTest { Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, null); Assert.assertEquals(property3.baseType, "Date"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -112,7 +112,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -141,7 +141,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"{}"*/null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -170,7 +170,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"{}"*/null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -193,7 +193,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -217,7 +217,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.name, "children"); Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "Children"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isNotContainer); } @@ -246,7 +246,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"[]"*/null); Assert.assertEquals(property.baseType, "Array"); Assert.assertEquals(property.containerType, "array"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); } @@ -276,9 +276,9 @@ public class JavaScriptModelTest { Assert.assertEquals(property.defaultValue, /*"{}"*/ null); Assert.assertEquals(property.baseType, "Object"); Assert.assertEquals(property.containerType, "map"); - Assert.assertNull(property.required); + Assert.assertFalse(property.required); Assert.assertTrue(property.isContainer); - Assert.assertNull(property.isNotContainer); + Assert.assertFalse(property.isNotContainer); } @Test(description = "convert an array model") @@ -336,7 +336,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.name, "NAME"); Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.required); Assert.assertTrue(property.isNotContainer); } @@ -362,7 +362,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.name, "pId"); Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.required); Assert.assertTrue(property.isNotContainer); } @@ -424,8 +424,8 @@ public class JavaScriptModelTest { Assert.assertEquals(property.name, "inputBinaryData"); Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); - Assert.assertNull(property.required); + Assert.assertFalse(property.hasMore); + Assert.assertFalse(property.required); Assert.assertTrue(property.isNotContainer); } @@ -449,7 +449,7 @@ public class JavaScriptModelTest { Assert.assertEquals(property.name, "u"); Assert.assertEquals(property.defaultValue, null); Assert.assertEquals(property.baseType, "String"); - Assert.assertNull(property.hasMore); + Assert.assertFalse(property.hasMore); Assert.assertTrue(property.isNotContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java index c2d0fd0f7af..7f74cdf1145 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -36,7 +36,7 @@ public class ObjcModelTest { Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -87,8 +87,8 @@ public class ObjcModelTest { Assert.assertEquals(property3.name, "createdAt"); Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "NSDate"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -125,9 +125,9 @@ public class ObjcModelTest { Assert.assertEquals(property2.name, "urls"); Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "NSArray"); - Assert.assertNull(property2.hasMore); + Assert.assertFalse(property2.hasMore); Assert.assertEquals(property2.containerType, "array"); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isPrimitiveType); Assert.assertTrue(property2.isContainer); } @@ -153,7 +153,7 @@ public class ObjcModelTest { Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); Assert.assertTrue(property1.isPrimitiveType); } @@ -177,7 +177,7 @@ public class ObjcModelTest { Assert.assertEquals(property1.datatype, "SWGChildren*"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "SWGChildren"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -202,7 +202,7 @@ public class ObjcModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "NSArray"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -228,9 +228,9 @@ public class ObjcModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "NSDictionary"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } @Test(description = "convert an array model") @@ -299,7 +299,7 @@ public class ObjcModelTest { final Model definition = model.getDefinitions().get("AnimalFarm"); final CodegenModel codegenModel = codegen.fromModel("AnimalFarm",definition); - Assert.assertEquals(codegenModel.isArrayModel,Boolean.TRUE); + Assert.assertEquals(codegenModel.isArrayModel, true); Assert.assertEquals(codegenModel.arrayModelType,"SWGAnimal"); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java index 035daa9bf33..0d121315e85 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -78,8 +78,8 @@ public class PhpModelTest { Assert.assertEquals(property3.name, "created_at"); Assert.assertEquals(property3.defaultValue, null); Assert.assertEquals(property3.baseType, "\\DateTime"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -115,9 +115,9 @@ public class PhpModelTest { Assert.assertEquals(property2.datatype, "string[]"); Assert.assertEquals(property2.name, "urls"); Assert.assertEquals(property2.baseType, "array"); - Assert.assertNull(property2.hasMore); + Assert.assertFalse(property2.hasMore); Assert.assertEquals(property2.containerType, "array"); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isPrimitiveType); Assert.assertTrue(property2.isContainer); } @@ -143,7 +143,7 @@ public class PhpModelTest { Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); Assert.assertTrue(property1.isPrimitiveType); } @@ -166,7 +166,7 @@ public class PhpModelTest { Assert.assertEquals(property1.datatype, "\\Swagger\\Client\\Model\\Children"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -190,7 +190,7 @@ public class PhpModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "array"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -217,9 +217,9 @@ public class PhpModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } @Test(description = "convert an array model") @@ -320,7 +320,7 @@ public class PhpModelTest { Assert.assertEquals(prope.datatypeWithEnum, "ENUM_INTEGER"); Assert.assertEquals(prope.enumName, "ENUM_INTEGER"); Assert.assertTrue(prope.isEnum); - Assert.assertNull(prope.isContainer); + Assert.assertFalse(prope.isContainer); Assert.assertNull(prope.items); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java index 5478200ca9c..cde532e6135 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java @@ -95,8 +95,8 @@ public class PythonTest { Assert.assertEquals(property3.name, "created_at"); Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "datetime"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -133,9 +133,9 @@ public class PythonTest { Assert.assertEquals(property2.name, "urls"); Assert.assertNull(property2.defaultValue); Assert.assertEquals(property2.baseType, "list"); - Assert.assertNull(property2.hasMore); + Assert.assertFalse(property2.hasMore); Assert.assertEquals(property2.containerType, "array"); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isPrimitiveType); Assert.assertTrue(property2.isContainer); } @@ -161,7 +161,7 @@ public class PythonTest { Assert.assertEquals(property1.name, "translations"); Assert.assertEquals(property1.baseType, "dict"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); Assert.assertTrue(property1.isPrimitiveType); } @@ -184,7 +184,7 @@ public class PythonTest { Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -209,7 +209,7 @@ public class PythonTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "list"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -235,9 +235,9 @@ public class PythonTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "dict"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java index e3c12d028fb..95e08c6b362 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java @@ -70,8 +70,8 @@ public class ScalaModelTest { Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); Assert.assertEquals(property3.baseType, "DateTime"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -100,7 +100,7 @@ public class ScalaModelTest { Assert.assertEquals(property1.defaultValue, "new ListBuffer[String]() "); Assert.assertEquals(property1.baseType, "List"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -128,7 +128,7 @@ public class ScalaModelTest { Assert.assertEquals(property1.defaultValue, "new HashMap[String, String]() "); Assert.assertEquals(property1.baseType, "Map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -153,7 +153,7 @@ public class ScalaModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.defaultValue, "null"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -181,7 +181,7 @@ public class ScalaModelTest { Assert.assertEquals(property1.defaultValue, "new ListBuffer[Children]() "); Assert.assertEquals(property1.baseType, "List"); Assert.assertEquals(property1.containerType, "array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -210,9 +210,9 @@ public class ScalaModelTest { Assert.assertEquals(property1.defaultValue, "new HashMap[String, Children]() "); Assert.assertEquals(property1.baseType, "Map"); Assert.assertEquals(property1.containerType, "map"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); - Assert.assertNull(property1.isNotContainer); + Assert.assertFalse(property1.isNotContainer); } @Test(description = "convert an array model") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java index c3d2d829c9c..43f7103f312 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift/SwiftModelTest.java @@ -62,7 +62,7 @@ public class SwiftModelTest { Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "NSDate"); Assert.assertTrue(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); final CodegenProperty property4 = cm.vars.get(3); @@ -72,7 +72,7 @@ public class SwiftModelTest { Assert.assertNull(property4.defaultValue); Assert.assertEquals(property4.baseType, "NSData"); Assert.assertTrue(property4.hasMore); - Assert.assertNull(property4.required); + Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); final CodegenProperty property5 = cm.vars.get(4); @@ -82,7 +82,7 @@ public class SwiftModelTest { Assert.assertNull(property5.defaultValue); Assert.assertEquals(property5.baseType, "NSData"); Assert.assertTrue(property5.hasMore); - Assert.assertNull(property5.required); + Assert.assertFalse(property5.required); Assert.assertTrue(property5.isNotContainer); final CodegenProperty property6 = cm.vars.get(5); @@ -91,8 +91,8 @@ public class SwiftModelTest { Assert.assertEquals(property6.name, "uuid"); Assert.assertNull(property6.defaultValue); Assert.assertEquals(property6.baseType, "NSUUID"); - Assert.assertNull(property6.hasMore); - Assert.assertNull(property6.required); + Assert.assertFalse(property6.hasMore); + Assert.assertFalse(property6.required); Assert.assertTrue(property6.isNotContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java index 4d3f59992f3..277d16ad654 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3ModelTest.java @@ -64,7 +64,7 @@ public class Swift3ModelTest { Assert.assertNull(property3.defaultValue); Assert.assertEquals(property3.baseType, "Date"); Assert.assertTrue(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); final CodegenProperty property4 = cm.vars.get(3); @@ -74,7 +74,7 @@ public class Swift3ModelTest { Assert.assertNull(property4.defaultValue); Assert.assertEquals(property4.baseType, "Data"); Assert.assertTrue(property4.hasMore); - Assert.assertNull(property4.required); + Assert.assertFalse(property4.required); Assert.assertTrue(property4.isNotContainer); final CodegenProperty property5 = cm.vars.get(4); @@ -84,7 +84,7 @@ public class Swift3ModelTest { Assert.assertNull(property5.defaultValue); Assert.assertEquals(property5.baseType, "Data"); Assert.assertTrue(property5.hasMore); - Assert.assertNull(property5.required); + Assert.assertFalse(property5.required); Assert.assertTrue(property5.isNotContainer); final CodegenProperty property6 = cm.vars.get(5); @@ -93,8 +93,8 @@ public class Swift3ModelTest { Assert.assertEquals(property6.name, "uuid"); Assert.assertNull(property6.defaultValue); Assert.assertEquals(property6.baseType, "UUID"); - Assert.assertNull(property6.hasMore); - Assert.assertNull(property6.required); + Assert.assertFalse(property6.hasMore); + Assert.assertFalse(property6.required); Assert.assertTrue(property6.isNotContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java index f6eb8cb2b63..d5125805adb 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/fetch/TypeScriptFetchModelTest.java @@ -70,8 +70,8 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -105,8 +105,8 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property2.datatype, "Array"); Assert.assertEquals(property2.name, "urls"); Assert.assertEquals(property2.baseType, "Array"); - Assert.assertNull(property2.hasMore); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.hasMore); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isContainer); } @@ -129,7 +129,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.defaultValue, "null"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -153,7 +153,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(property1.datatype, "Array"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } @@ -233,7 +233,7 @@ public class TypeScriptFetchModelTest { Assert.assertEquals(prope.datatypeWithEnum, "EnumIntegerEnum"); Assert.assertEquals(prope.enumName, "EnumIntegerEnum"); Assert.assertTrue(prope.isEnum); - Assert.assertNull(prope.isContainer); + Assert.assertFalse(prope.isContainer); Assert.assertNull(prope.items); Assert.assertEquals(prope.allowableValues.get("values"), Arrays.asList(1, -1)); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index 75ab210966d..b7dacc22357 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -63,8 +63,8 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -98,8 +98,8 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property2.datatype, "Array"); Assert.assertEquals(property2.name, "urls"); Assert.assertEquals(property2.baseType, "Array"); - Assert.assertNull(property2.hasMore); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.hasMore); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isContainer); } @@ -122,7 +122,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.defaultValue, "null"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -146,7 +146,7 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(property1.datatype, "Array"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java index 685495f03c2..4d6a7dcb3b9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular2/TypeScriptAngular2ModelTest.java @@ -64,8 +64,8 @@ public class TypeScriptAngular2ModelTest { Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -99,8 +99,8 @@ public class TypeScriptAngular2ModelTest { Assert.assertEquals(property2.datatype, "Array"); Assert.assertEquals(property2.name, "urls"); Assert.assertEquals(property2.baseType, "Array"); - Assert.assertNull(property2.hasMore); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.hasMore); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isContainer); } @@ -123,7 +123,7 @@ public class TypeScriptAngular2ModelTest { Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.defaultValue, "null"); Assert.assertEquals(property1.baseType, "models.Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -147,7 +147,7 @@ public class TypeScriptAngular2ModelTest { Assert.assertEquals(property1.datatype, "Array"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java index 37e4fb688e0..18fb8e256bb 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptnode/TypeScriptNodeModelTest.java @@ -63,8 +63,8 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property3.datatype, "Date"); Assert.assertEquals(property3.name, "createdAt"); Assert.assertEquals(property3.defaultValue, "null"); - Assert.assertNull(property3.hasMore); - Assert.assertNull(property3.required); + Assert.assertFalse(property3.hasMore); + Assert.assertFalse(property3.required); Assert.assertTrue(property3.isNotContainer); } @@ -98,8 +98,8 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property2.datatype, "Array"); Assert.assertEquals(property2.name, "urls"); Assert.assertEquals(property2.baseType, "Array"); - Assert.assertNull(property2.hasMore); - Assert.assertNull(property2.required); + Assert.assertFalse(property2.hasMore); + Assert.assertFalse(property2.required); Assert.assertTrue(property2.isContainer); } @@ -121,7 +121,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property1.datatype, "Children"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Children"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -145,7 +145,7 @@ public class TypeScriptNodeModelTest { Assert.assertEquals(property1.datatype, "Array"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Array"); - Assert.assertNull(property1.required); + Assert.assertFalse(property1.required); Assert.assertTrue(property1.isContainer); } From 78e2435f42fa3c48fec37f0cb72b91e75bda4793 Mon Sep 17 00:00:00 2001 From: Cliffano Subagio Date: Sun, 11 Dec 2016 17:25:33 +1100 Subject: [PATCH 149/269] Add Shine Solutions to list of companies using Swagger Codegen (#4363) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 1280b9f9d6f..7e0d636da50 100644 --- a/README.md +++ b/README.md @@ -809,6 +809,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Royal Bank of Canada (RBC)](http://www.rbc.com/canada.html) - [Saritasa](https://www.saritasa.com/) - [SCOOP Software GmbH](http://www.scoop-software.de) +- [Shine Solutions](https://shinesolutions.com/) - [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) - [StyleRecipe](http://stylerecipe.co.jp) From 2e6eb43c26a26a29658e7955770bdae2557daa7c Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 11 Dec 2016 14:26:58 +0800 Subject: [PATCH 150/269] add SRC --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 7e0d636da50..ed8afe1dfe7 100644 --- a/README.md +++ b/README.md @@ -812,6 +812,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Shine Solutions](https://shinesolutions.com/) - [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) +- [SRC](https://www.src.si/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) - [TaskData](http://www.taskdata.com/) From 8e200970d48bf2dce6dfaccc4ae7a1d034fbe007 Mon Sep 17 00:00:00 2001 From: Frederick Cai Date: Sun, 11 Dec 2016 23:38:12 +1300 Subject: [PATCH 151/269] [typescript-angular2] build to dist folder --- .../resources/typescript-angular2/tsconfig.mustache | 4 ++-- .../petstore/typescript-angular2/default/api/PetApi.ts | 10 +++++----- .../client/petstore/typescript-angular2/npm/README.md | 4 ++-- .../petstore/typescript-angular2/npm/api/PetApi.ts | 10 +++++----- .../petstore/typescript-angular2/npm/package.json | 2 +- .../petstore/typescript-angular2/npm/tsconfig.json | 4 ++-- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/tsconfig.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/tsconfig.mustache index 07fbdf7e1b1..3db6e8690e9 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/tsconfig.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/tsconfig.mustache @@ -9,7 +9,7 @@ "moduleResolution": "node", "removeComments": true, "sourceMap": true, - "outDir": "./lib", + "outDir": "./dist", "noLib": false, "declaration": true }, @@ -17,7 +17,7 @@ "node_modules", "typings/main.d.ts", "typings/main", - "lib" + "dist" ], "filesGlob": [ "./model/*.ts", diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 70ab123c5a5..e44ced10fb8 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -415,17 +415,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 1c4f0c5bd4f..cea650043ba 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612112338 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612112338 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 70ab123c5a5..e44ced10fb8 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -415,17 +415,17 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index eeeca81bcbb..c19fb8509a4 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201612061134", + "version": "0.0.1-SNAPSHOT.201612112338", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ diff --git a/samples/client/petstore/typescript-angular2/npm/tsconfig.json b/samples/client/petstore/typescript-angular2/npm/tsconfig.json index 07fbdf7e1b1..3db6e8690e9 100644 --- a/samples/client/petstore/typescript-angular2/npm/tsconfig.json +++ b/samples/client/petstore/typescript-angular2/npm/tsconfig.json @@ -9,7 +9,7 @@ "moduleResolution": "node", "removeComments": true, "sourceMap": true, - "outDir": "./lib", + "outDir": "./dist", "noLib": false, "declaration": true }, @@ -17,7 +17,7 @@ "node_modules", "typings/main.d.ts", "typings/main", - "lib" + "dist" ], "filesGlob": [ "./model/*.ts", From c2a4c558c88415e5b1c8d4164f7facb440eef139 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 12 Dec 2016 15:44:15 +0800 Subject: [PATCH 152/269] add delete cmd for appveyor --- appveyor.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/appveyor.yml b/appveyor.yml index b69ac912f94..48bc666a0b6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -18,6 +18,7 @@ install: - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5 + - cmd: RMDIR "C:\projects\swagger-codegen\swagger-samples" /S /Q - git clone https://github.com/wing328/swagger-samples - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs" build_script: From 562ff1a4e1d695eac2cd96fc9027c6dbf1cdf18a Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 12 Dec 2016 17:13:20 +0800 Subject: [PATCH 153/269] Minor fix to issue with Appveyor (#4365) * show current folder in appveyor ci * remove cache * comment out folder delete --- appveyor.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index 48bc666a0b6..ee8df16d712 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -18,7 +18,8 @@ install: - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET M2_HOME=C:\maven\apache-maven-3.2.5 - - cmd: RMDIR "C:\projects\swagger-codegen\swagger-samples" /S /Q + - cmd: dir/w +# - cmd: RMDIR "C:\projects\swagger-codegen\swagger-samples" /S /Q - git clone https://github.com/wing328/swagger-samples - ps: Start-Process -FilePath 'C:\maven\apache-maven-3.2.5\bin\mvn' -ArgumentList 'jetty:run' -WorkingDirectory "$env:appveyor_build_folder\swagger-samples\java\java-jersey-jaxrs" build_script: @@ -38,6 +39,6 @@ test_script: # generate all petstore clients - .\bin\windows\run-all-petstore.cmd -cache: +#cache: # - C:\maven\ # - C:\Users\appveyor\.m2 From f4fb79822ff4d5a647cf5cf3eb310f96957f840f Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 12 Dec 2016 17:42:08 +0800 Subject: [PATCH 154/269] Add CircleCI configuration in preparation for CI test migration (#4367) * add codeship yml * rename ci config * show rvm version * use ruby-2.1.0 * check ruby version * use rvm default * fix host name * set node version * test mvn clean install * use -q for mvn * set memory limit * add export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m" * run test only * update MaxPermSize to 256mb * run mvn verify * remove -q * add comment * add more comment * restore ruby model order --- circle.yml | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 circle.yml diff --git a/circle.yml b/circle.yml new file mode 100644 index 00000000000..dadbcaca009 --- /dev/null +++ b/circle.yml @@ -0,0 +1,44 @@ +# work in progress: the goal is to move all the existing tests +# handled by travis-ci to circle CI so that travis-ci can test +# objc/swift API client instead +machine: + environment: + _JAVA_OPTIONS: "-Xms512m -Xmx1024m" + java: + # TODO we also need to test oraclejdk8 + version: oraclejdk7 + node: + version: 5.0.0 + services: + - docker + # Override /etc/hosts + hosts: + petstore.swagger.io: 127.0.0.1 + +dependencies: + cache_directories: + - ~/.jspm + - ~/.npm + - ~/builder + - ~/.m2 + pre: + - export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m" + - gem install bundler + - npm install -g typescript + - sudo pip install virtualenv + # to run petstore server locally via docker + - docker pull swaggerapi/petstore + - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore + - docker ps -a + # show host table to confirm petstore.swagger.io is mapped to localhost + - cat /etc/hosts + override: + #- rvm --default use 2.1.0 + #- ruby -v + +test: + override: + - mvn verify -Psamples + #- mvn -q clean install + #- jdk_switcher use oraclejdk8 + #- mvn -q clean install From bf50ea13662770de9f2a6546fa2cd40e83ba1aee Mon Sep 17 00:00:00 2001 From: Dmitry Solovyov Date: Mon, 12 Dec 2016 05:38:39 -0500 Subject: [PATCH 155/269] fix the value for @Generated java annotation (#4366) com.my.Generator.class.toString() returns "class com.my.Generator", and this value is then used in the javax.annotation.Generated annotation like that: @Generated(value = "class com.my.Generator"). Should use Generator.class.getName() instead, so we end up with @Generated(value = "com.my.Generator") --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 667b6342b9b..5f11f99d99c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -113,7 +113,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { config.processOpts(); config.preprocessSwagger(swagger); config.additionalProperties().put("generatedDate", DateTime.now().toString()); - config.additionalProperties().put("generatorClass", config.getClass().toString()); + config.additionalProperties().put("generatorClass", config.getClass().getName()); config.additionalProperties().put("inputSpec", config.getInputSpec()); if (swagger.getVendorExtensions() != null) { config.vendorExtensions().putAll(swagger.getVendorExtensions()); From 77b92d7d11de6874aea5bf9a1f9d7d53b2a0b31e Mon Sep 17 00:00:00 2001 From: Paul Vollmer Date: Mon, 12 Dec 2016 17:19:20 +0100 Subject: [PATCH 156/269] Fix go client auth UserName var issue (#4245) --- modules/swagger-codegen/src/main/resources/go/api.mustache | 2 +- .../src/main/resources/go/configuration.mustache | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index ef388bcf278..186fe556c06 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -64,7 +64,7 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} {{/isApiKey}} {{#isBasic}} // http basic authentication required - if a.Configuration.UserName != "" || a.Configuration.Password != ""{ + if a.Configuration.Username != "" || a.Configuration.Password != ""{ localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() } {{/isBasic}} diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache index 6f56b2138fb..bd3ce67afca 100644 --- a/modules/swagger-codegen/src/main/resources/go/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -9,7 +9,7 @@ import ( type Configuration struct { - UserName string `json:"userName,omitempty"` + Username string `json:"userName,omitempty"` Password string `json:"password,omitempty"` APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` APIKey map[string]string `json:"APIKey,omitempty"` @@ -42,7 +42,7 @@ func NewConfiguration() *Configuration { } func (c *Configuration) GetBasicAuthEncodedString() string { - return base64.StdEncoding.EncodeToString([]byte(c.UserName + ":" + c.Password)) + return base64.StdEncoding.EncodeToString([]byte(c.Username + ":" + c.Password)) } func (c *Configuration) AddDefaultHeader(key string, value string) { From 0b5a6f25da7cae7781858fdb113aa678098e4dba Mon Sep 17 00:00:00 2001 From: Chris Putnam Date: Mon, 12 Dec 2016 11:39:09 -0500 Subject: [PATCH 157/269] [typescript-angular2] access token function (#4361) * allow function so access token can be derived for each api call * update tests * update type for accessToken to be string or function that returns string --- .../typescript-angular2/api.mustache | 5 +- .../configuration.mustache | 2 +- .../typescript-angular2/api/FakeApi.ts | 135 ++++++++++++------ .../typescript-angular2/configuration.ts | 6 + .../typescript-angular2/index.ts | 4 +- .../typescript-angular2/model/ModelReturn.ts | 28 +--- .../typescript-angular2/variables.ts | 3 + .../typescript-angular2/default/api/PetApi.ts | 50 +++++-- .../default/configuration.ts | 2 +- 9 files changed, 152 insertions(+), 83 deletions(-) create mode 100644 samples/client/petstore-security-test/typescript-angular2/configuration.ts create mode 100644 samples/client/petstore-security-test/typescript-angular2/variables.ts diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 6f085fe3411..8700083b63d 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -143,7 +143,10 @@ export class {{classname}} { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } {{/isOAuth}} {{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache index 94989933b63..dd8d4be9728 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string; + accessToken: string | () => string; } \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts index 88b8e7a6562..1cbd4d97048 100644 --- a/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts +++ b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts @@ -1,72 +1,67 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ -import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; -import {Injectable, Optional} from '@angular/core'; -import {Observable} from 'rxjs/Observable'; -import * as models from '../model/models'; -import 'rxjs/Rx'; +import { Inject, Injectable, Optional } from '@angular/core'; +import { Http, Headers, URLSearchParams } from '@angular/http'; +import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; +import { Response, ResponseContentType } from '@angular/http'; + +import { Observable } from 'rxjs/Observable'; +import 'rxjs/add/operator/map'; + +import * as models from '../model/models'; +import { BASE_PATH } from '../variables'; +import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ -'use strict'; @Injectable() export class FakeApi { - protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; - public defaultHeaders : Headers = new Headers(); + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'; + public defaultHeaders: Headers = new Headers(); + public configuration: Configuration = new Configuration(); - constructor(protected http: Http, @Optional() basePath: string) { + constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } + if (configuration) { + this.configuration = configuration; + } } /** - * To test code injection *_/ ' \" =end \\r\\n \\n \\r * - * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + * Extends object by coping non-existing properties. + * @param objA object to be extended + * @param objB source object */ - public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : Observable<{}> { - const path = this.basePath + '/fake'; + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + (objA as any)[key] = (objB as any)[key]; + } + } + return objA; + } - let queryParameters = new URLSearchParams(); - let headerParams = this.defaultHeaders; - let formParams = new URLSearchParams(); - - headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); - - formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; - - let requestOptions: RequestOptionsArgs = { - method: 'PUT', - headers: headerParams, - search: queryParameters - }; - requestOptions.body = formParams.toString(); - - return this.http.request(path, requestOptions) + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR(test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any): Observable<{}> { + return this.testCodeInjectEndRnNRWithHttpInfo(test code inject * ' " =end rn n r, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; @@ -76,4 +71,54 @@ export class FakeApi { }); } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + */ + public testCodeInjectEndRnNRWithHttpInfo(test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any): Observable { + const path = this.basePath + `/fake`; + + let queryParameters = new URLSearchParams(); + let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 + let formParams = new URLSearchParams(); + + + + // to determine the Content-Type header + let consumes: string[] = [ + 'application/json', + '*_/ =end -- ' + ]; + + // to determine the Accept header + let produces: string[] = [ + 'application/json', + '*_/ =end -- ' + ]; + + + headers.set('Content-Type', 'application/x-www-form-urlencoded'); + + + if (test code inject * ' " =end rn n r !== undefined) { + formParams.set('test code inject */ ' " =end -- \r\n \n \r', test code inject * ' " =end rn n r); + } + + let requestOptions: RequestOptionsArgs = new RequestOptions({ + method: RequestMethod.Put, + headers: headers, + body: formParams.toString(), + search: queryParameters + }); + + // https://github.com/swagger-api/swagger-codegen/issues/4037 + if (extraHttpRequestParams) { + requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + } + + return this.http.request(path, requestOptions); + } + } diff --git a/samples/client/petstore-security-test/typescript-angular2/configuration.ts b/samples/client/petstore-security-test/typescript-angular2/configuration.ts new file mode 100644 index 00000000000..dd8d4be9728 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/configuration.ts @@ -0,0 +1,6 @@ +export class Configuration { + apiKey: string; + username: string; + password: string; + accessToken: string | () => string; +} \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/index.ts b/samples/client/petstore-security-test/typescript-angular2/index.ts index 557365516ad..d097c728017 100644 --- a/samples/client/petstore-security-test/typescript-angular2/index.ts +++ b/samples/client/petstore-security-test/typescript-angular2/index.ts @@ -1,2 +1,4 @@ export * from './api/api'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; +export * from './variables'; +export * from './configuration'; \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts index 23c982f6888..5e9e114be05 100644 --- a/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts +++ b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts @@ -1,38 +1,24 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ -'use strict'; import * as models from './models'; /** - * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + * Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r */ export interface ModelReturn { - - /** - * property description *_/ ' \" =end \\r\\n \\n \\r + * property description *_/ ' \" =end -- \\r\\n \\n \\r */ return?: number; + } diff --git a/samples/client/petstore-security-test/typescript-angular2/variables.ts b/samples/client/petstore-security-test/typescript-angular2/variables.ts new file mode 100644 index 00000000000..27b987e9b23 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/variables.ts @@ -0,0 +1,3 @@ +import { OpaqueToken } from '@angular/core'; + +export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 70ab123c5a5..5751b452369 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -217,7 +217,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -271,7 +274,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -320,7 +326,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -369,7 +378,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -415,16 +427,19 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); + } + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); } @@ -472,7 +487,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -529,7 +547,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } headers.set('Content-Type', 'application/x-www-form-urlencoded'); @@ -592,7 +613,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } headers.set('Content-Type', 'application/x-www-form-urlencoded'); diff --git a/samples/client/petstore/typescript-angular2/default/configuration.ts b/samples/client/petstore/typescript-angular2/default/configuration.ts index 94989933b63..dd8d4be9728 100644 --- a/samples/client/petstore/typescript-angular2/default/configuration.ts +++ b/samples/client/petstore/typescript-angular2/default/configuration.ts @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string; + accessToken: string | () => string; } \ No newline at end of file From 15a84259aa956ab6d2bdd08f999c4418a640777d Mon Sep 17 00:00:00 2001 From: Dmitry Solovyov Date: Mon, 12 Dec 2016 22:08:14 -0500 Subject: [PATCH 158/269] added Upwork to users list (#4378) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index ed8afe1dfe7..b49bf4994ff 100644 --- a/README.md +++ b/README.md @@ -817,6 +817,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Svenska Spel AB](https://www.svenskaspel.se/) - [TaskData](http://www.taskdata.com/) - [ThoughtWorks](https://www.thoughtworks.com) +- [Upwork](http://upwork.com/) - [uShip](https://www.uship.com/) - [VMware](https://vmware.com/) - [W.UP](http://wup.hu/?siteLang=en) From da9d64d053057709bb52d2136e818199d3f01fe5 Mon Sep 17 00:00:00 2001 From: Scott Richter Date: Tue, 13 Dec 2016 02:01:48 -0500 Subject: [PATCH 159/269] Fix for issue #4370 - Cpprest does not set Content-Type header on POST requests. (#4374) * Fixed cpprest generator to include Content-Type header in requests. * Fixing indent to use spaces. --- .../resources/cpprest/api-source.mustache | 5 +- samples/client/petstore/cpprest/ApiClient.cpp | 4 +- samples/client/petstore/cpprest/ApiClient.h | 4 +- .../petstore/cpprest/ApiConfiguration.cpp | 4 +- .../petstore/cpprest/ApiConfiguration.h | 4 +- .../client/petstore/cpprest/ApiException.cpp | 4 +- .../client/petstore/cpprest/ApiException.h | 4 +- .../client/petstore/cpprest/HttpContent.cpp | 4 +- samples/client/petstore/cpprest/HttpContent.h | 4 +- samples/client/petstore/cpprest/IHttpBody.h | 4 +- samples/client/petstore/cpprest/JsonBody.cpp | 4 +- samples/client/petstore/cpprest/JsonBody.h | 4 +- samples/client/petstore/cpprest/ModelBase.cpp | 4 +- samples/client/petstore/cpprest/ModelBase.h | 4 +- .../petstore/cpprest/MultipartFormData.cpp | 4 +- .../petstore/cpprest/MultipartFormData.h | 4 +- .../client/petstore/cpprest/api/PetApi.cpp | 171 +++++++++++------- samples/client/petstore/cpprest/api/PetApi.h | 21 +-- .../client/petstore/cpprest/api/StoreApi.cpp | 73 +++++--- .../client/petstore/cpprest/api/StoreApi.h | 8 +- .../client/petstore/cpprest/api/UserApi.cpp | 153 +++++++++++----- samples/client/petstore/cpprest/api/UserApi.h | 14 +- .../petstore/cpprest/model/Category.cpp | 4 +- .../client/petstore/cpprest/model/Category.h | 8 +- .../client/petstore/cpprest/model/Order.cpp | 4 +- samples/client/petstore/cpprest/model/Order.h | 8 +- samples/client/petstore/cpprest/model/Pet.cpp | 4 +- samples/client/petstore/cpprest/model/Pet.h | 14 +- samples/client/petstore/cpprest/model/Tag.cpp | 4 +- samples/client/petstore/cpprest/model/Tag.h | 8 +- .../client/petstore/cpprest/model/User.cpp | 4 +- samples/client/petstore/cpprest/model/User.h | 8 +- 32 files changed, 349 insertions(+), 222 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache index 72a91ebc64a..e72567efa67 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -180,7 +180,10 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r else { throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; {{#authMethods}} // authentication ({{name}}) required diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index 8cd09d423ae..f0a93eaa6f7 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 3e1a42dc0d3..5e7ed98350e 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index 1520a56d347..ddbc1bc3eb2 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index 66e9501610d..290f1fc7edf 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp index 5ddf808f9f0..8e3646eb973 100644 --- a/samples/client/petstore/cpprest/ApiException.cpp +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index fa67da92ab4..96b1d03da00 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp index e9a619d7753..b6e9ff911c1 100644 --- a/samples/client/petstore/cpprest/HttpContent.cpp +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index 04d477f2743..9bcee47cc41 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 6ebbf38f5d9..336ae2e98d2 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp index 63bb10ca3a5..4586cb8c055 100644 --- a/samples/client/petstore/cpprest/JsonBody.cpp +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index 75e2dbca71c..d9c0f1598cc 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index c897549d565..399e1a49c31 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index 24e392e870d..b2fb4f1118f 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp index 9d38ec0add0..e0c6b54a0b8 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.cpp +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index ee1a002b56f..3f633c20958 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index 6d78ed575ce..daff60c39a4 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -39,12 +39,6 @@ PetApi::~PetApi() pplx::task PetApi::addPet(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->addPet")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -55,13 +49,18 @@ pplx::task PetApi::addPet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -118,7 +117,10 @@ consumeHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(415, U("PetApi->addPet does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -171,13 +173,18 @@ pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -224,7 +231,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("PetApi->deletePet does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -276,13 +286,18 @@ pplx::task>> PetApi::findPetsByStatus(std::vect std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -325,7 +340,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("PetApi->findPetsByStatus does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -403,13 +421,18 @@ pplx::task>> PetApi::findPetsByTags(std::vector std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -429,7 +452,7 @@ responseHttpContentTypes.insert( U("application/json") ); { - queryParams[U("tags")] = ApiClient::parameterToArrayString<>(tags); + queryParams[U("tags")] = ApiClient::parameterToArrayString(tags); } @@ -452,7 +475,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("PetApi->findPetsByTags does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -531,13 +557,18 @@ pplx::task> PetApi::getPetById(int64_t petId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -579,8 +610,13 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required + // oauth2 authentication is added automatically as part of the http_client_config // authentication (api_key) required { utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); @@ -645,12 +681,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task PetApi::updatePet(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->updatePet")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); @@ -661,13 +691,18 @@ pplx::task PetApi::updatePet(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -724,7 +759,10 @@ consumeHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(415, U("PetApi->updatePet does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -763,7 +801,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); return void(); }); } -pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status) +pplx::task PetApi::updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status) { @@ -777,13 +815,18 @@ pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -836,7 +879,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("PetApi->updatePetWithForm does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -875,7 +921,7 @@ responseHttpContentTypes.insert( U("application/json") ); return void(); }); } -pplx::task> PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) +pplx::task PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) { @@ -890,11 +936,17 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -947,7 +999,10 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili else { throw ApiException(415, U("PetApi->uploadFile does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config @@ -983,26 +1038,8 @@ pplx::task> PetApi::uploadFile(int64_t petId, utili }) .then([=](utility::string_t response) { - std::shared_ptr result(new ApiResponse()); - - if(responseHttpContentType == U("application/json")) - { - web::json::value json = web::json::value::parse(response); - - result->fromJson(json); - } - // else if(responseHttpContentType == U("multipart/form-data")) - // { - // TODO multipart response parsing - // } - else - { - throw ApiException(500 - , U("error calling findPetsByStatus: unsupported response type")); - } - - return result; - }); + return void(); + }); } } diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index 3ec4e8971d8..b0714fef286 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -22,7 +22,6 @@ #include "ApiClient.h" -#include "ApiResponse.h" #include "HttpContent.h" #include "Pet.h" #include @@ -45,7 +44,7 @@ public: /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task addPet(std::shared_ptr body); /// /// Deletes a pet @@ -61,7 +60,7 @@ public: /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (optional, default to available) pplx::task>> findPetsByStatus(std::vector status); /// /// Finds Pets by tags @@ -69,15 +68,15 @@ public: /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// - /// Tags to filter by + /// Tags to filter by (optional) pplx::task>> findPetsByTags(std::vector tags); /// /// Find pet by ID /// /// - /// Returns a single pet + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// - /// ID of pet to return + /// ID of pet that needs to be fetched pplx::task> getPetById(int64_t petId); /// /// Update an existing pet @@ -85,7 +84,7 @@ public: /// /// /// - /// Pet object that needs to be added to the store + /// Pet object that needs to be added to the store (optional) pplx::task updatePet(std::shared_ptr body); /// /// Updates a pet in the store with form data @@ -94,7 +93,7 @@ public: /// /// /// ID of pet that needs to be updated/// Updated name of the pet (optional)/// Updated status of the pet (optional) - pplx::task updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status); + pplx::task updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status); /// /// uploads an image /// @@ -102,7 +101,7 @@ public: /// /// /// ID of pet to update/// Additional data to pass to server (optional)/// file to upload (optional) - pplx::task> uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); + pplx::task uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); protected: std::shared_ptr m_ApiClient; diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index 889da5dfbb8..83187645cc4 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -50,13 +50,18 @@ pplx::task StoreApi::deleteOrder(utility::string_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -98,7 +103,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("StoreApi->deleteOrder does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -149,11 +157,17 @@ pplx::task> StoreApi::getInventory() std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -191,7 +205,10 @@ pplx::task> StoreApi::getInventory() else { throw ApiException(415, U("StoreApi->getInventory does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; // authentication (api_key) required { @@ -260,7 +277,7 @@ pplx::task> StoreApi::getInventory() return result; }); } -pplx::task> StoreApi::getOrderById(int64_t orderId) +pplx::task> StoreApi::getOrderById(utility::string_t orderId) { @@ -274,13 +291,18 @@ pplx::task> StoreApi::getOrderById(int64_t orderId) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -322,7 +344,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("StoreApi->getOrderById does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -380,12 +405,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task> StoreApi::placeOrder(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order"); @@ -396,13 +415,18 @@ pplx::task> StoreApi::placeOrder(std::shared_ptr b std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -457,7 +481,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("StoreApi->placeOrder does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index e20fcc6dd21..96632ea40b0 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -61,14 +61,14 @@ public: /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - pplx::task> getOrderById(int64_t orderId); + pplx::task> getOrderById(utility::string_t orderId); /// /// Place an order for a pet /// /// /// /// - /// order placed for purchasing the pet + /// order placed for purchasing the pet (optional) pplx::task> placeOrder(std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index 2d65d7a4ba8..32f1c51d1fb 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -39,12 +39,6 @@ UserApi::~UserApi() pplx::task UserApi::createUser(std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->createUser")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user"); @@ -55,13 +49,18 @@ pplx::task UserApi::createUser(std::shared_ptr body) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -116,7 +115,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->createUser does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -166,13 +168,18 @@ pplx::task UserApi::createUsersWithArrayInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -241,7 +248,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->createUsersWithArrayInput does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -291,13 +301,18 @@ pplx::task UserApi::createUsersWithListInput(std::vector> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -366,7 +381,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->createUsersWithListInput does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -417,13 +435,18 @@ pplx::task UserApi::deleteUser(utility::string_t username) std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -465,7 +488,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->deleteUser does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -516,13 +542,18 @@ pplx::task> UserApi::getUserByName(utility::string_t usern std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -564,7 +595,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->getUserByName does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -632,13 +666,18 @@ pplx::task UserApi::loginUser(utility::string_t username, uti std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("text/plain"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -647,6 +686,11 @@ responseHttpContentTypes.insert( U("application/json") ); { responseHttpContentType = U("multipart/form-data"); } + // plain text + else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) + { + responseHttpContentType = U("text/plain"); + } else { throw ApiException(400, U("UserApi->loginUser does not produce any supported media type")); @@ -686,7 +730,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->loginUser does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -729,6 +776,10 @@ responseHttpContentTypes.insert( U("application/json") ); result = ModelBase::stringFromJson(json); } + else if(responseHttpContentType == U("text/plain")) + { + result = response; + } // else if(responseHttpContentType == U("multipart/form-data")) // { // TODO multipart response parsing @@ -755,13 +806,18 @@ pplx::task UserApi::logoutUser() std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -799,7 +855,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->logoutUser does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) @@ -839,12 +898,6 @@ responseHttpContentTypes.insert( U("application/json") ); pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr body) { - // verify the required parameter 'body' is set - if (body == nullptr) - { - throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->updateUser")); - } - std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); @@ -856,13 +909,18 @@ pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr std::map> fileParams; std::unordered_set responseHttpContentTypes; - responseHttpContentTypes.insert( U("application/xml") ); -responseHttpContentTypes.insert( U("application/json") ); + responseHttpContentTypes.insert( U("application/json") ); +responseHttpContentTypes.insert( U("application/xml") ); utility::string_t responseHttpContentType; // use JSON if possible - if ( responseHttpContentTypes.size() == 0 || responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) + if ( responseHttpContentTypes.size() == 0 ) + { + responseHttpContentType = U("application/json"); + } + // JSON + else if ( responseHttpContentTypes.find(U("application/json")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("application/json"); } @@ -921,7 +979,10 @@ responseHttpContentTypes.insert( U("application/json") ); else { throw ApiException(415, U("UserApi->updateUser does not consume any supported media type")); - } + } + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; return m_ApiClient->callApi(path, U("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index a57aee858da..530d70aba0f 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -44,7 +44,7 @@ public: /// /// This can only be done by the logged in user. /// - /// Created user object + /// Created user object (optional) pplx::task createUser(std::shared_ptr body); /// /// Creates list of users with given input array @@ -52,7 +52,7 @@ public: /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithArrayInput(std::vector> body); /// /// Creates list of users with given input array @@ -60,7 +60,7 @@ public: /// /// /// - /// List of user object + /// List of user object (optional) pplx::task createUsersWithListInput(std::vector> body); /// /// Delete user @@ -84,7 +84,7 @@ public: /// /// /// - /// The user name for login/// The password for login in clear text + /// The user name for login (optional)/// The password for login in clear text (optional) pplx::task loginUser(utility::string_t username, utility::string_t password); /// /// Logs out current logged in user session @@ -100,7 +100,7 @@ public: /// /// This can only be done by the logged in user. /// - /// name that need to be deleted/// Updated user object + /// name that need to be deleted/// Updated user object (optional) pplx::task updateUser(utility::string_t username, std::shared_ptr body); protected: diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 2adfb1050f2..6350dc0a72e 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index f2a3125c196..d3ef9b99b48 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -13,7 +13,7 @@ /* * Category.h * - * A category for a pet + * */ #ifndef Category_H_ @@ -30,7 +30,7 @@ namespace client { namespace model { /// -/// A category for a pet +/// /// class Category : public ModelBase diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index 9c09ad426c2..87aa74ed5f0 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index 59e8af4db4d..2728a17c29a 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -13,7 +13,7 @@ /* * Order.h * - * An order for a pets from the pet store + * */ #ifndef Order_H_ @@ -30,7 +30,7 @@ namespace client { namespace model { /// -/// An order for a pets from the pet store +/// /// class Order : public ModelBase diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 76f527de4a1..47d4528e01e 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index e888bbe2eb8..d9411f3797a 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -13,7 +13,7 @@ /* * Pet.h * - * A pet for sale in the pet store + * */ #ifndef Pet_H_ @@ -22,10 +22,10 @@ #include "ModelBase.h" -#include "Category.h" -#include -#include #include "Tag.h" +#include +#include "Category.h" +#include namespace io { namespace swagger { @@ -33,7 +33,7 @@ namespace client { namespace model { /// -/// A pet for sale in the pet store +/// /// class Pet : public ModelBase diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 1621474bce7..22fba97c0b9 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 6fb1283b9af..40edb4f1ee9 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -13,7 +13,7 @@ /* * Tag.h * - * A tag for a pet + * */ #ifndef Tag_H_ @@ -30,7 +30,7 @@ namespace client { namespace model { /// -/// A tag for a pet +/// /// class Tag : public ModelBase diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index be11cdfeaa4..fa19cbe64c3 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index a48a93c4752..58def69adde 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -13,7 +13,7 @@ /* * User.h * - * A User who is purchasing from the pet store + * */ #ifndef User_H_ @@ -30,7 +30,7 @@ namespace client { namespace model { /// -/// A User who is purchasing from the pet store +/// /// class User : public ModelBase From beeb02a2dccca2368e4ff1a8c836956bdf99c766 Mon Sep 17 00:00:00 2001 From: weiyang Date: Tue, 13 Dec 2016 15:52:22 +0800 Subject: [PATCH 160/269] [html] Add type anchor to body param block (#4368) * [html] Add type anchor to 'bodyParam' block Signed-off-by: weiyang * [html][samples] Add type anchor to 'bodyParam' block Signed-off-by: weiyang --- .../resources/htmlDocs/bodyParam.mustache | 4 +- samples/html/index.html | 107 ++++++++++-------- 2 files changed, 59 insertions(+), 52 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache index 45b0373e9c5..9af8790a0e0 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache @@ -1,3 +1,3 @@ -{{#isBodyParam}}
    {{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
    +{{#isBodyParam}}
    {{baseName}} {{#baseType}}{{baseType}}{{/baseType}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
    -
    Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
    {{/isBodyParam}} \ No newline at end of file +
    Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
    {{/isBodyParam}} diff --git a/samples/html/index.html b/samples/html/index.html index 850fa5752d0..5d4bf9f1493 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -246,9 +246,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body Pet (required)
    Body Parameter — Pet object that needs to be added to the store
    +
    @@ -355,18 +356,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    [ {
    -  "photoUrls" : [ "aeiou" ],
    -  "name" : "doggie",
    +  "tags" : [ {
    +    "id" : 123456789,
    +    "name" : "aeiou"
    +  } ],
       "id" : 123456789,
       "category" : {
    -    "name" : "aeiou",
    -    "id" : 123456789
    +    "id" : 123456789,
    +    "name" : "aeiou"
       },
    -  "tags" : [ {
    -    "name" : "aeiou",
    -    "id" : 123456789
    -  } ],
    -  "status" : "aeiou"
    +  "status" : "aeiou",
    +  "name" : "doggie",
    +  "photoUrls" : [ "aeiou" ]
     } ]

    Produces

    @@ -428,18 +429,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    [ {
    -  "photoUrls" : [ "aeiou" ],
    -  "name" : "doggie",
    +  "tags" : [ {
    +    "id" : 123456789,
    +    "name" : "aeiou"
    +  } ],
       "id" : 123456789,
       "category" : {
    -    "name" : "aeiou",
    -    "id" : 123456789
    +    "id" : 123456789,
    +    "name" : "aeiou"
       },
    -  "tags" : [ {
    -    "name" : "aeiou",
    -    "id" : 123456789
    -  } ],
    -  "status" : "aeiou"
    +  "status" : "aeiou",
    +  "name" : "doggie",
    +  "photoUrls" : [ "aeiou" ]
     } ]

    Produces

    @@ -501,18 +502,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "photoUrls" : [ "aeiou" ],
    -  "name" : "doggie",
    +  "tags" : [ {
    +    "id" : 123456789,
    +    "name" : "aeiou"
    +  } ],
       "id" : 123456789,
       "category" : {
    -    "name" : "aeiou",
    -    "id" : 123456789
    +    "id" : 123456789,
    +    "name" : "aeiou"
       },
    -  "tags" : [ {
    -    "name" : "aeiou",
    -    "id" : 123456789
    -  } ],
    -  "status" : "aeiou"
    +  "status" : "aeiou",
    +  "name" : "doggie",
    +  "photoUrls" : [ "aeiou" ]
     }

    Produces

    @@ -552,9 +553,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body Pet (required)
    Body Parameter — Pet object that needs to be added to the store
    +
    @@ -677,9 +679,9 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    +  "message" : "aeiou",
       "code" : 123,
    -  "type" : "aeiou",
    -  "message" : "aeiou"
    +  "type" : "aeiou"
     }

    Produces

    @@ -816,12 +818,12 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "petId" : 123456789,
    -  "quantity" : 123,
       "id" : 123456789,
    -  "shipDate" : "2000-01-23T04:56:07.000+00:00",
    +  "petId" : 123456789,
       "complete" : true,
    -  "status" : "aeiou"
    +  "status" : "aeiou",
    +  "quantity" : 123,
    +  "shipDate" : "2000-01-23T04:56:07.000+00:00"
     }

    Produces

    @@ -855,9 +857,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body Order (required)
    Body Parameter — order placed for purchasing the pet
    +
    @@ -884,12 +887,12 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "petId" : 123456789,
    -  "quantity" : 123,
       "id" : 123456789,
    -  "shipDate" : "2000-01-23T04:56:07.000+00:00",
    +  "petId" : 123456789,
       "complete" : true,
    -  "status" : "aeiou"
    +  "status" : "aeiou",
    +  "quantity" : 123,
    +  "shipDate" : "2000-01-23T04:56:07.000+00:00"
     }

    Produces

    @@ -921,9 +924,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body User (required)
    Body Parameter — Created user object
    +
    @@ -958,9 +962,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body User (required)
    Body Parameter — List of user object
    +
    @@ -995,9 +1000,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body User (required)
    Body Parameter — List of user object
    +
    @@ -1103,14 +1109,14 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "firstName" : "aeiou",
    -  "lastName" : "aeiou",
    -  "password" : "aeiou",
    -  "userStatus" : 123,
    -  "phone" : "aeiou",
       "id" : 123456789,
    +  "lastName" : "aeiou",
    +  "phone" : "aeiou",
    +  "username" : "aeiou",
       "email" : "aeiou",
    -  "username" : "aeiou"
    +  "userStatus" : 123,
    +  "firstName" : "aeiou",
    +  "password" : "aeiou"
     }

    Produces

    @@ -1234,9 +1240,10 @@ font-style: italic;

    Request body

    -
    body (required)
    +
    body User (required)
    Body Parameter — Updated user object
    +
    From 7719bc8f1d964530b9c4ee8b4d1173a8032ca428 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 13 Dec 2016 16:09:15 +0800 Subject: [PATCH 161/269] add https://github.com/bbatsov/clojure-style-guide --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5a169cd7682..67d2b7f0ffb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -32,6 +32,7 @@ Code change should conform to the programming style guide of the respective lang - Android: https://source.android.com/source/code-style.html - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html +- Clojure: https://github.com/bbatsov/clojure-style-guide - Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - Java: https://google.github.io/styleguide/javaguide.html - JavaScript: https://github.com/airbnb/javascript/tree/master/es5 From 5818f2c88213d2a20c4140bbb694313cd9f9e904 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 13 Dec 2016 16:09:56 +0800 Subject: [PATCH 162/269] [C++] better code format for `cpprest` templates (#4379) * replace tab with 4-space in cpprest templates * remove trailing whitespaces from templates * fix code indentation in cpprest templates * remove empty block in cpprest templates --- .../resources/cpprest/api-header.mustache | 10 +- .../resources/cpprest/api-source.mustache | 170 +++--- .../cpprest/apiclient-header.mustache | 36 +- .../cpprest/apiclient-source.mustache | 146 +++--- .../cpprest/apiconfiguration-header.mustache | 18 +- .../cpprest/apiexception-header.mustache | 10 +- .../resources/cpprest/git_push.sh.mustache | 2 +- .../cpprest/httpcontent-header.mustache | 8 +- .../cpprest/ihttpbody-header.mustache | 4 +- .../cpprest/jsonbody-header.mustache | 8 +- .../cpprest/jsonbody-source.mustache | 2 +- .../resources/cpprest/model-header.mustache | 20 +- .../resources/cpprest/model-source.mustache | 36 +- .../cpprest/modelbase-header.mustache | 12 +- .../cpprest/modelbase-source.mustache | 30 +- .../cpprest/multipart-header.mustache | 6 +- .../cpprest/multipart-source.mustache | 6 +- samples/client/petstore/cpprest/ApiClient.cpp | 150 +++--- samples/client/petstore/cpprest/ApiClient.h | 40 +- .../petstore/cpprest/ApiConfiguration.cpp | 4 +- .../petstore/cpprest/ApiConfiguration.h | 22 +- .../client/petstore/cpprest/ApiException.cpp | 4 +- .../client/petstore/cpprest/ApiException.h | 14 +- .../client/petstore/cpprest/HttpContent.cpp | 4 +- samples/client/petstore/cpprest/HttpContent.h | 12 +- samples/client/petstore/cpprest/IHttpBody.h | 8 +- samples/client/petstore/cpprest/JsonBody.cpp | 6 +- samples/client/petstore/cpprest/JsonBody.h | 12 +- samples/client/petstore/cpprest/ModelBase.cpp | 34 +- samples/client/petstore/cpprest/ModelBase.h | 16 +- .../petstore/cpprest/MultipartFormData.cpp | 10 +- .../petstore/cpprest/MultipartFormData.h | 10 +- .../client/petstore/cpprest/api/PetApi.cpp | 484 ++++++++---------- samples/client/petstore/cpprest/api/PetApi.h | 31 +- .../client/petstore/cpprest/api/StoreApi.cpp | 244 ++++----- .../client/petstore/cpprest/api/StoreApi.h | 18 +- .../client/petstore/cpprest/api/UserApi.cpp | 452 ++++++++-------- samples/client/petstore/cpprest/api/UserApi.h | 24 +- samples/client/petstore/cpprest/git_push.sh | 2 +- .../petstore/cpprest/model/ApiResponse.cpp | 26 +- .../petstore/cpprest/model/ApiResponse.h | 20 +- .../petstore/cpprest/model/Category.cpp | 22 +- .../client/petstore/cpprest/model/Category.h | 28 +- .../client/petstore/cpprest/model/Order.cpp | 36 +- samples/client/petstore/cpprest/model/Order.h | 28 +- samples/client/petstore/cpprest/model/Pet.cpp | 48 +- samples/client/petstore/cpprest/model/Pet.h | 32 +- samples/client/petstore/cpprest/model/Tag.cpp | 22 +- samples/client/petstore/cpprest/model/Tag.h | 28 +- .../client/petstore/cpprest/model/User.cpp | 64 +-- samples/client/petstore/cpprest/model/User.h | 28 +- 51 files changed, 1230 insertions(+), 1277 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache index 02880a18859..94fc2cc9517 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-header.mustache @@ -1,10 +1,10 @@ {{>licenseInfo}} {{#operations}}/* * {{classname}}.h - * + * * {{description}} */ - + #ifndef {{classname}}_H_ #define {{classname}}_H_ @@ -35,11 +35,11 @@ public: {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{/allParams}} pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} - + protected: - std::shared_ptr m_ApiClient; + std::shared_ptr m_ApiClient; }; - + {{#apiNamespaceDeclarations}} } {{/apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache index e72567efa67..30724132edb 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/api-source.mustache @@ -35,23 +35,24 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r throw ApiException(400, U("Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}")); } {{/isContainer}}{{/isPrimitiveType}}{{/required}}{{/allParams}} - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("{{path}}"); {{#pathParams}}boost::replace_all(path, U("{") U("{{baseName}}") U("}"), ApiClient::parameterToString({{{paramName}}})); {{/pathParams}} - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; - {{#produces}}responseHttpContentTypes.insert( U("{{mediaType}}") ); + {{#produces}} + responseHttpContentTypes.insert( U("{{mediaType}}") ); {{/produces}} - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -67,13 +68,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); } {{#vendorExtensions.x-codegen-response.isString}} - // plain text + // plain text else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("text/plain"); @@ -90,41 +91,70 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r else { throw ApiException(400, U("{{classname}}->{{operationId}} does not produce any supported media type")); - } - {{/vendorExtensions.x-codegen-response-ishttpcontent}} - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - {{#consumes}}consumeHttpContentTypes.insert( U("{{mediaType}}") ); - {{/consumes}} - - {{#allParams}}{{^isBodyParam}}{{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}} - { - {{#isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); - {{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); - {{/isHeaderParam}}{{#isFormParam}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); - {{/isFile}}{{/isFormParam}}{{/isContainer}}{{^isContainer}}{{#isQueryParam}}queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); - {{/isQueryParam}}{{#isHeaderParam}}headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); - {{/isHeaderParam}}{{#isFormParam}}{{#isFile}}fileParams[ U("{{baseName}}") ] = {{paramName}}; - {{/isFile}}{{^isFile}}formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}}); - {{/isFile}}{{/isFormParam}}{{/isContainer}} } - {{/isBodyParam}}{{/allParams}} + {{/vendorExtensions.x-codegen-response-ishttpcontent}} + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + {{#consumes}} + consumeHttpContentTypes.insert( U("{{mediaType}}") ); + {{/consumes}} + + {{#allParams}} + {{^isBodyParam}} + {{^isPathParam}} + {{^isPrimitiveType}}{{^isContainer}}if ({{paramName}} != nullptr){{/isContainer}}{{/isPrimitiveType}} + { + {{#isContainer}} + {{#isQueryParam}} + queryParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isQueryParam}} + {{#isHeaderParam}} + headerParams[U("{{baseName}}")] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isHeaderParam}} + {{#isFormParam}} + {{^isFile}} + formParams[ U("{{baseName}}") ] = ApiClient::parameterToArrayString<{{items.datatype}}>({{paramName}}); + {{/isFile}} + {{/isFormParam}} + {{/isContainer}} + {{^isContainer}} + {{#isQueryParam}} + queryParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + {{/isQueryParam}} + {{#isHeaderParam}} + headerParams[U("{{baseName}}")] = ApiClient::parameterToString({{paramName}}); + {{/isHeaderParam}} + {{#isFormParam}} + {{#isFile}} + fileParams[ U("{{baseName}}") ] = {{paramName}}; + {{/isFile}} + {{^isFile}} + formParams[ U("{{baseName}}") ] = ApiClient::parameterToString({{paramName}}); + {{/isFile}} + {{/isFormParam}} + {{/isContainer}} + } + {{/isPathParam}} + {{/isBodyParam}} + {{/allParams}} std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - {{#bodyParam}} web::json::value json; - - {{#isPrimitiveType}} json = ModelBase::toJson({{paramName}}); - {{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}} + + {{#isPrimitiveType}} + json = ModelBase::toJson({{paramName}}); + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isListContainer}} { std::vector jsonArray; for( auto& item : {{paramName}} ) @@ -137,22 +167,26 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r } json = web::json::value::array(jsonArray); } - {{/isListContainer}}{{^isListContainer}}json = ModelBase::toJson({{paramName}}); - {{/isListContainer}}{{/isPrimitiveType}} - + {{/isListContainer}} + {{^isListContainer}} + json = ModelBase::toJson({{paramName}}); + {{/isListContainer}} + {{/isPrimitiveType}} + httpBody = std::shared_ptr( new JsonBody( json ) ); - {{/bodyParam}} } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - {{#bodyParam}} std::shared_ptr multipart(new MultipartFormData); - {{#isPrimitiveType}} multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}})); - {{/isPrimitiveType}}{{^isPrimitiveType}}{{#isListContainer}} + {{#isPrimitiveType}} + multipart->add(ModelBase::toHttpContent("{{paramName}}", {{paramName}})); + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isListContainer}} { std::vector jsonArray; for( auto& item : {{paramName}} ) @@ -165,13 +199,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r } multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), web::json::value::array(jsonArray), U("application/json"))); } - {{/isListContainer}}{{^isListContainer}}{{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}})); - {{/isString}}{{^isString}} + {{/isListContainer}} + {{^isListContainer}} + {{#isString}}multipart->add(ModelBase::toHttpContent(U("{{paramName}}"), {{paramName}})); + {{/isString}} + {{^isString}} if({{paramName}}.get()) { {{paramName}}->toMultipart(multipart, U("{{paramName}}")); } - {{/isString}}{{/isListContainer}}{{/isPrimitiveType}} + {{/isString}} + {{/isListContainer}} + {{/isPrimitiveType}} httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -181,10 +220,10 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r { throw ApiException(415, U("{{classname}}->{{operationId}} does not consume any supported media type")); } - + //Set the request content type in the header. headerParams[U("Content-Type")] = requestHttpContentType; - + {{#authMethods}} // authentication ({{name}}) required {{#isApiKey}} @@ -214,13 +253,13 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r // oauth2 authentication is added automatically as part of the http_client_config {{/isOAuth}} {{/authMethods}} - + return m_ApiClient->callApi(path, U("{{httpMethod}}"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -229,7 +268,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r , U("error calling {{operationId}}: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -241,7 +280,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r , std::make_shared(response.extract_utf8string(true).get())); } } - + {{#vendorExtensions.x-codegen-response-ishttpcontent}} return response.extract_vector(); }) @@ -257,21 +296,28 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r }) .then([=](utility::string_t response) { - {{^returnType}}return void(); - {{/returnType}}{{#returnType}}{{#returnContainer}}{{{returnType}}} result; - {{/returnContainer}}{{^returnContainer}}{{{returnType}}} result({{{defaultResponse}}});{{/returnContainer}} - + {{^returnType}} + return void(); + {{/returnType}} + {{#returnType}} + {{#returnContainer}} + {{{returnType}}} result; + {{/returnContainer}} + {{^returnContainer}} + {{{returnType}}} result({{{defaultResponse}}}); + {{/returnContainer}} + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + {{#isListContainer}}for( auto& item : json.as_array() ) { - {{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item)); - {{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item)); + {{#vendorExtensions.x-codegen-response.items.isPrimitiveType}}result.push_back(ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(item)); + {{/vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.items.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.items.isString}}result.push_back(ModelBase::stringFromJson(item)); {{/vendorExtensions.x-codegen-response.items.isString}}{{^vendorExtensions.x-codegen-response.items.isString}}{{{vendorExtensions.x-codegen-response.items.datatype}}} itemObj({{{vendorExtensions.x-codegen-response.items.defaultValue}}}); itemObj->fromJson(item); - result.push_back(itemObj); + result.push_back(itemObj); {{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}} } {{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}for( auto& item : json.as_object() ) @@ -282,7 +328,7 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r itemObj->fromJson(item); result[item.first] = itemObj; {{/vendorExtensions.x-codegen-response.items.isString}}{{/vendorExtensions.x-codegen-response.items.isPrimitiveType}} - } + } {{/isMapContainer}}{{^isMapContainer}}{{#vendorExtensions.x-codegen-response.isPrimitiveType}}result = ModelBase::{{vendorExtensions.x-codegen-response.items.datatype}}FromJson(json); {{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{^vendorExtensions.x-codegen-response.isPrimitiveType}}{{#vendorExtensions.x-codegen-response.isString}}result = ModelBase::stringFromJson(json); {{/vendorExtensions.x-codegen-response.isString}}{{^vendorExtensions.x-codegen-response.isString}}result->fromJson(json);{{/vendorExtensions.x-codegen-response.isString}}{{/vendorExtensions.x-codegen-response.isPrimitiveType}}{{/isMapContainer}}{{/isListContainer}} @@ -293,18 +339,18 @@ pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/r }{{/vendorExtensions.x-codegen-response.isString}} // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; {{/returnType}} {{/vendorExtensions.x-codegen-response-ishttpcontent}} - }); + }); } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache index ba975f01155..466f914d4a9 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * ApiClient.h - * - * This is an API client responsible for stating the HTTP calls + * + * This is an API client responsible for stating the HTTP calls */ #ifndef ApiClient_H_ @@ -14,8 +14,8 @@ #include "IHttpBody.h" #include "HttpContent.h" -#include -#include +#include +#include #include #include @@ -31,39 +31,39 @@ class {{declspec}} ApiClient public: ApiClient( std::shared_ptr configuration = nullptr ); virtual ~ApiClient(); - + std::shared_ptr getConfiguration() const; void setConfiguration(std::shared_ptr configuration); - + static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); - + template static utility::string_t parameterToArrayString(std::vector value) { utility::stringstream_t ss; - + for( size_t i = 0; i < value.size(); i++) { if( i > 0) ss << U(", "); ss << ApiClient::parameterToString(value[i]); } - return ss.str(); + return ss.str(); } - - pplx::task callApi( - const utility::string_t& path, - const utility::string_t& method, - const std::map& queryParams, - const std::shared_ptr postBody, - const std::map& headerParams, - const std::map& formParams, + + pplx::task callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, const std::map>& fileParams, const utility::string_t& contentType ) const; - + protected: std::shared_ptr m_Configuration; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache index a13771f4311..e9a3810c7bd 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -40,91 +40,91 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } -pplx::task ApiClient::callApi( - const utility::string_t& path, - const utility::string_t& method, - const std::map& queryParams, +pplx::task ApiClient::callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, const std::shared_ptr postBody, - const std::map& headerParams, - const std::map& formParams, + const std::map& headerParams, + const std::map& formParams, const std::map>& fileParams, const utility::string_t& contentType ) const { - if (postBody != nullptr && formParams.size() != 0) - { - throw ApiException(400, U("Cannot have body and form params")); - } + if (postBody != nullptr && formParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and form params")); + } - if (postBody != nullptr && fileParams.size() != 0) - { - throw ApiException(400, U("Cannot have body and file params")); - } + if (postBody != nullptr && fileParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and file params")); + } - if (fileParams.size() > 0 && contentType != U("multipart/form-data")) - { - throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); - } + if (fileParams.size() > 0 && contentType != U("multipart/form-data")) + { + throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); + } - web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); + web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); - web::http::http_request request; - for ( auto& kvp : headerParams ) - { - request.headers().add(kvp.first, kvp.second); - } + web::http::http_request request; + for ( auto& kvp : headerParams ) + { + request.headers().add(kvp.first, kvp.second); + } - if (fileParams.size() > 0) - { - MultipartFormData uploadData; - for (auto& kvp : formParams) - { - uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); - } - for (auto& kvp : fileParams) - { - uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); - } - std::stringstream data; - postBody->writeTo(data); - auto bodyString = data.str(); - auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); - } - else - { - if (postBody != nullptr) - { - std::stringstream data; - postBody->writeTo(data); - auto bodyString = data.str(); - auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); - } - else - { - web::http::uri_builder formData; - for (auto& kvp : formParams) - { - formData.append_query(kvp.first, kvp.second); - } - request.set_body(formData.query(), U("application/x-www-form-urlencoded")); - } - } + if (fileParams.size() > 0) + { + MultipartFormData uploadData; + for (auto& kvp : formParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + for (auto& kvp : fileParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + if (postBody != nullptr) + { + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + web::http::uri_builder formData; + for (auto& kvp : formParams) + { + formData.append_query(kvp.first, kvp.second); + } + request.set_body(formData.query(), U("application/x-www-form-urlencoded")); + } + } - web::http::uri_builder builder(path); - for (auto& kvp : queryParams) - { - builder.append_query(kvp.first, kvp.second); - } - request.set_request_uri(builder.to_uri()); - request.set_method(method); - if ( !request.headers().has( web::http::header_names::user_agent ) ) - { - request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); - } + web::http::uri_builder builder(path); + for (auto& kvp : queryParams) + { + builder.append_query(kvp.first, kvp.second); + } + request.set_request_uri(builder.to_uri()); + request.set_method(method); + if ( !request.headers().has( web::http::header_names::user_agent ) ) + { + request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); + } - return client.request(request); + return client.request(request); } {{#apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache index 32411f41180..c554fb21bfc 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiconfiguration-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * ApiConfiguration.h - * - * This class represents a single item of a multipart-formdata request. + * + * This class represents a single item of a multipart-formdata request. */ #ifndef ApiConfiguration_H_ @@ -12,7 +12,7 @@ #include -#include +#include #include {{#apiNamespaceDeclarations}} namespace {{this}} { @@ -23,18 +23,18 @@ class {{declspec}} ApiConfiguration public: ApiConfiguration(); virtual ~ApiConfiguration(); - + web::http::client::http_client_config& getHttpConfig(); void setHttpConfig( web::http::client::http_client_config& value ); - + utility::string_t getBaseUrl() const; void setBaseUrl( const utility::string_t value ); - + utility::string_t getUserAgent() const; void setUserAgent( const utility::string_t value ); - + std::map& getDefaultHeaders(); - + utility::string_t getApiKey( const utility::string_t& prefix) const; void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ); @@ -43,7 +43,7 @@ protected: std::map m_DefaultHeaders; std::map m_ApiKeys; web::http::client::http_client_config m_HttpConfig; - utility::string_t m_UserAgent; + utility::string_t m_UserAgent; }; {{#apiNamespaceDeclarations}} diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache index 483d7dab423..cc01d446ddf 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiexception-header.mustache @@ -1,7 +1,7 @@ {{>licenseInfo}} /* * ApiException.h - * + * * This is the exception being thrown in case the api call was not successful */ @@ -10,7 +10,7 @@ {{{defaultInclude}}} -#include +#include #include #include @@ -33,12 +33,12 @@ public: , std::map& headers , std::shared_ptr content = nullptr ); virtual ~ApiException(); - + std::map& getHeaders(); std::shared_ptr getContent() const; - + protected: - std::shared_ptr m_Content; + std::shared_ptr m_Content; std::map m_Headers; }; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache index 2619d82f14d..c7d7c390acf 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/git_push.sh.mustache @@ -28,7 +28,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache index 27f53b8e0c1..004971cf7f6 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/httpcontent-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * HttpContent.h - * - * This class represents a single item of a multipart-formdata request. + * + * This class represents a single item of a multipart-formdata request. */ #ifndef HttpContent_H_ @@ -12,7 +12,7 @@ #include -#include +#include {{#modelNamespaceDeclarations}} namespace {{this}} { @@ -38,7 +38,7 @@ public: virtual std::shared_ptr getData(); virtual void setData( std::shared_ptr value ); - + virtual void writeTo( std::ostream& stream ); protected: diff --git a/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache index 34604e0048e..76e5f211e86 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/ihttpbody-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * IHttpBody.h - * - * This is the interface for contents that can be sent to a remote HTTP server. + * + * This is the interface for contents that can be sent to a remote HTTP server. */ #ifndef IHttpBody_H_ diff --git a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache index 4a146c5373d..4face5a0dd6 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * JsonBody.h - * - * This is a JSON http body which can be submitted via http + * + * This is a JSON http body which can be submitted via http */ #ifndef JsonBody_H_ @@ -11,7 +11,7 @@ {{{defaultInclude}}} #include "IHttpBody.h" -#include +#include {{#modelNamespaceDeclarations}} namespace {{this}} { @@ -25,7 +25,7 @@ public: virtual ~JsonBody(); void writeTo( std::ostream& target ) override; - + protected: web::json::value m_Json; }; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache index 05074527b28..091bcd0007b 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/jsonbody-source.mustache @@ -7,7 +7,7 @@ namespace {{this}} { JsonBody::JsonBody( const web::json::value& json) : m_Json(json) -{ +{ } JsonBody::~JsonBody() diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache index 9515743a8ff..4dc426e76ca 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-header.mustache @@ -1,7 +1,7 @@ {{>licenseInfo}} {{#models}}{{#model}}/* * {{classname}}.h - * + * * {{description}} */ @@ -22,15 +22,15 @@ namespace {{this}} { /// {{description}} ///
    class {{declspec}} {{classname}} - : public ModelBase + : public ModelBase { public: {{classname}}(); virtual ~{{classname}}(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -38,10 +38,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// {{classname}} members - + + ///////////////////////////////////////////// + /// {{classname}} members + {{#vars}} /// /// {{description}} @@ -53,7 +53,7 @@ public: void unset{{name}}(); {{/required}} {{/vars}} - + protected: {{#vars}}{{{datatype}}} m_{{name}}; {{^required}}bool m_{{name}}IsSet; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache index 26970c20d8d..cee24dc406c 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/model-source.mustache @@ -20,7 +20,7 @@ namespace {{this}} { { } -void {{classname}}::validate() +void {{classname}}::validate() { // TODO: implement validation } @@ -28,7 +28,7 @@ void {{classname}}::validate() web::json::value {{classname}}::toJson() const { web::json::value val = web::json::value::object(); - + {{#vars}}{{#isPrimitiveType}}{{^isListContainer}}{{^required}}if(m_{{name}}IsSet) { val[U("{{baseName}}")] = ModelBase::toJson(m_{{name}}); @@ -42,7 +42,7 @@ web::json::value {{classname}}::toJson() const } {{#required}}val[U("{{baseName}}")] = web::json::value::array(jsonArray); {{/required}}{{^required}} - if(jsonArray.size() > 0) + if(jsonArray.size() > 0) { val[U("{{baseName}}")] = web::json::value::array(jsonArray); } @@ -77,7 +77,7 @@ void {{classname}}::fromJson(web::json::value& val) {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} - if(item.is_null()) + if(item.is_null()) { m_{{name}}.push_back( {{{items.datatype}}}(nullptr) ); } @@ -89,7 +89,7 @@ void {{classname}}::fromJson(web::json::value& val) } {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } - {{^required}} + {{^required}} } {{/required}} } @@ -97,13 +97,13 @@ void {{classname}}::fromJson(web::json::value& val) { {{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); - {{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null()) + {{/isDateTime}}{{^isDateTime}}if(!val[U("{{baseName}}")].is_null()) { {{{datatype}}} newItem({{{defaultValue}}}); newItem->fromJson(val[U("{{baseName}}")]); {{setter}}( newItem ); } - {{/isDateTime}}{{/isString}} + {{/isDateTime}}{{/isString}} } {{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromJson(val[U("{{baseName}}")])); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromJson(val[U("{{baseName}}")])); @@ -135,7 +135,7 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co } {{#required}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); {{/required}}{{^required}} - if(jsonArray.size() > 0) + if(jsonArray.size() > 0) { multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), web::json::value::array(jsonArray), U("application/json"))); } @@ -149,7 +149,7 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co { m_{{name}}->toMultipart(multipart, U("{{baseName}}.")); } - {{/isDateTime}}{{/isString}} + {{/isDateTime}}{{/isString}} } {{/required}}{{#required}}{{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); {{/isString}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + U("{{baseName}}"), m_{{name}})); @@ -174,9 +174,9 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{/required}}{{/isListContainer}}{{/isPrimitiveType}}{{#isListContainer}}{ m_{{name}}.clear(); {{^required}}if(multipart->hasContent(U("{{baseName}}"))) - { + { {{/required}} - + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); for( auto& item : jsonArray.as_array() ) { @@ -184,7 +184,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{/isPrimitiveType}}{{^isPrimitiveType}}{{#items.isString}}m_{{name}}.push_back(ModelBase::stringFromJson(item)); {{/items.isString}}{{^items.isString}}{{#items.isDateTime}}m_{{name}}.push_back(ModelBase::dateFromJson(item)); {{/items.isDateTime}}{{^items.isDateTime}} - if(item.is_null()) + if(item.is_null()) { m_{{name}}.push_back( {{{items.datatype}}}(nullptr) ); } @@ -196,7 +196,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, } {{/items.isDateTime}}{{/items.isString}}{{/isPrimitiveType}} } - {{^required}} + {{^required}} } {{/required}} } @@ -210,7 +210,7 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, newItem->fromMultiPart(multipart, U("{{baseName}}.")); {{setter}}( newItem ); } - {{/isDateTime}}{{/isString}} + {{/isDateTime}}{{/isString}} } {{/required}}{{#required}}{{#isString}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(U("{{baseName}}")))); {{/isString}}{{^isString}}{{#isDateTime}}{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(U("{{baseName}}")))); @@ -220,8 +220,8 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart, {{setter}}( new{{name}} ); {{/vendorExtensions.x-codegen-file}}{{/isDateTime}}{{/isString}}{{/required}}{{/isPrimitiveType}}{{/isListContainer}}{{/vars}} } - - + + {{#vars}}{{^isNotContainer}}{{{datatype}}}& {{classname}}::{{getter}}() { return m_{{name}}; @@ -235,12 +235,12 @@ void {{classname}}::{{setter}}({{{datatype}}} value) m_{{name}} = value; {{^required}}m_{{name}}IsSet = true;{{/required}} } -{{/isNotContainer}} +{{/isNotContainer}} {{^required}}bool {{classname}}::{{baseName}}IsSet() const { return m_{{name}}IsSet; } -void {{classname}}::unset{{name}}() +void {{classname}}::unset{{name}}() { m_{{name}}IsSet = false; } diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache index 262b154acd7..3daf1d0dc9d 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-header.mustache @@ -1,7 +1,7 @@ {{>licenseInfo}} /* * ModelBase.h - * + * * This is the base class for all model classes */ @@ -13,7 +13,7 @@ #include "MultipartFormData.h" #include -#include +#include {{#modelNamespaceDeclarations}} namespace {{this}} { @@ -40,7 +40,7 @@ public: static web::json::value toJson( int32_t value ); static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); - + static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); static utility::string_t stringFromJson(web::json::value& val); @@ -48,7 +48,7 @@ public: static double doubleFromJson(web::json::value& val); static bool boolFromJson(web::json::value& val); static std::shared_ptr fileFromJson(web::json::value& val); - + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U("")); static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U("")); static std::shared_ptr toHttpContent( const utility::string_t& name, std::shared_ptr value ); @@ -56,14 +56,14 @@ public: static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") ); - + static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); static utility::string_t stringFromHttpContent(std::shared_ptr val); static utility::datetime dateFromHttpContent(std::shared_ptr val); static bool boolFromHttpContent(std::shared_ptr val); static double doubleFromHttpContent(std::shared_ptr val); - + static utility::string_t toBase64( utility::string_t value ); static utility::string_t toBase64( std::shared_ptr value ); diff --git a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache index 787e390d0fd..9c34ab37f7d 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/modelbase-source.mustache @@ -14,7 +14,7 @@ ModelBase::~ModelBase() web::json::value ModelBase::toJson( const utility::string_t& value ) { - return web::json::value::string(value); + return web::json::value::string(value); } web::json::value ModelBase::toJson( const utility::datetime& value ) { @@ -26,7 +26,7 @@ web::json::value ModelBase::toJson( int32_t value ) } web::json::value ModelBase::toJson( int64_t value ) { - return web::json::value::number(value); + return web::json::value::number(value); } web::json::value ModelBase::toJson( double value ) { @@ -46,7 +46,7 @@ web::json::value ModelBase::toJson( std::shared_ptr content ) std::shared_ptr ModelBase::fileFromJson(web::json::value& val) { std::shared_ptr content(new HttpContent); - + if(val.has_field(U("ContentDisposition"))) { content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) ); @@ -169,14 +169,14 @@ utility::string_t ModelBase::toBase64( std::shared_ptr value ) { case 1: value->read( read, 1 ); - temp = read[0] << 16; + temp = read[0] << 16; base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); base64.append( 2, Base64PadChar ); break; case 2: value->read( read, 2 ); - temp = read[0] << 16; + temp = read[0] << 16; temp += read[1] << 8; base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); @@ -191,7 +191,7 @@ utility::string_t ModelBase::toBase64( std::shared_ptr value ) std::shared_ptr ModelBase::fromBase64( const utility::string_t& encoded ) { std::shared_ptr result(new std::stringstream); - + char outBuf[3] = { 0 }; uint32_t temp = 0; @@ -201,9 +201,9 @@ std::shared_ptr ModelBase::fromBase64( const utility::string_t& en for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ ) { temp <<= 6; - if ( *cursor >= 0x41 && *cursor <= 0x5A ) + if ( *cursor >= 0x41 && *cursor <= 0x5A ) { - temp |= *cursor - 0x41; + temp |= *cursor - 0x41; } else if ( *cursor >= 0x61 && *cursor <= 0x7A ) { @@ -283,7 +283,7 @@ double ModelBase::doubleFromJson(web::json::value& val) int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); int64_t result = 0; ss >> result; @@ -292,7 +292,7 @@ int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr val) int32_t ModelBase::int32_tFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); int32_t result = 0; ss >> result; @@ -302,22 +302,22 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr { std::shared_ptr data = val->getData(); data->seekg( 0, data->beg ); - + std::string str((std::istreambuf_iterator(*data.get())), std::istreambuf_iterator()); - + return utility::conversions::to_string_t(str); } utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr val) { - utility::string_t str = ModelBase::stringFromHttpContent(val); + utility::string_t str = ModelBase::stringFromHttpContent(val); return utility::datetime::from_string(str, utility::datetime::ISO_8601); } bool ModelBase::boolFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); bool result = false; ss >> result; @@ -326,7 +326,7 @@ bool ModelBase::boolFromHttpContent(std::shared_ptr val) double ModelBase::doubleFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); double result = 0.0; ss >> result; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache index 0835ed92667..917b8cf3cc5 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-header.mustache @@ -1,8 +1,8 @@ {{>licenseInfo}} /* * MultipartFormData.h - * - * This class represents a container for building a application/x-multipart-formdata requests. + * + * This class represents a container for building a application/x-multipart-formdata requests. */ #ifndef MultipartFormData_H_ @@ -36,7 +36,7 @@ public: virtual std::shared_ptr getContent(const utility::string_t& name) const; virtual bool hasContent(const utility::string_t& name) const; virtual void writeTo( std::ostream& target ); - + protected: std::vector> m_Contents; utility::string_t m_Boundary; diff --git a/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache index 507bda51839..af0b86968d9 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/multipart-source.mustache @@ -1,9 +1,9 @@ {{>licenseInfo}} #include "MultipartFormData.h" -#include "ModelBase.h" +#include "ModelBase.h" #include -#include +#include {{#modelNamespaceDeclarations}} namespace {{this}} { @@ -82,7 +82,7 @@ void MultipartFormData::writeTo( std::ostream& target ) // body std::shared_ptr data = content->getData(); - + data->seekg( 0, data->end ); std::vector dataBytes( data->tellg() ); diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index f0a93eaa6f7..c7687e2851b 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -52,91 +52,91 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } -pplx::task ApiClient::callApi( - const utility::string_t& path, - const utility::string_t& method, - const std::map& queryParams, +pplx::task ApiClient::callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, const std::shared_ptr postBody, - const std::map& headerParams, - const std::map& formParams, + const std::map& headerParams, + const std::map& formParams, const std::map>& fileParams, const utility::string_t& contentType ) const { - if (postBody != nullptr && formParams.size() != 0) - { - throw ApiException(400, U("Cannot have body and form params")); - } + if (postBody != nullptr && formParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and form params")); + } - if (postBody != nullptr && fileParams.size() != 0) - { - throw ApiException(400, U("Cannot have body and file params")); - } + if (postBody != nullptr && fileParams.size() != 0) + { + throw ApiException(400, U("Cannot have body and file params")); + } - if (fileParams.size() > 0 && contentType != U("multipart/form-data")) - { - throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); - } + if (fileParams.size() > 0 && contentType != U("multipart/form-data")) + { + throw ApiException(400, U("Operations with file parameters must be called with multipart/form-data")); + } - web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); + web::http::client::http_client client(m_Configuration->getBaseUrl(), m_Configuration->getHttpConfig()); - web::http::http_request request; - for ( auto& kvp : headerParams ) - { - request.headers().add(kvp.first, kvp.second); - } + web::http::http_request request; + for ( auto& kvp : headerParams ) + { + request.headers().add(kvp.first, kvp.second); + } - if (fileParams.size() > 0) - { - MultipartFormData uploadData; - for (auto& kvp : formParams) - { - uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); - } - for (auto& kvp : fileParams) - { - uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); - } - std::stringstream data; - postBody->writeTo(data); - auto bodyString = data.str(); - auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); - } - else - { - if (postBody != nullptr) - { - std::stringstream data; - postBody->writeTo(data); - auto bodyString = data.str(); - auto length = bodyString.size(); - request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); - } - else - { - web::http::uri_builder formData; - for (auto& kvp : formParams) - { - formData.append_query(kvp.first, kvp.second); - } - request.set_body(formData.query(), U("application/x-www-form-urlencoded")); - } - } + if (fileParams.size() > 0) + { + MultipartFormData uploadData; + for (auto& kvp : formParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + for (auto& kvp : fileParams) + { + uploadData.add(ModelBase::toHttpContent(kvp.first, kvp.second)); + } + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + if (postBody != nullptr) + { + std::stringstream data; + postBody->writeTo(data); + auto bodyString = data.str(); + auto length = bodyString.size(); + request.set_body(concurrency::streams::bytestream::open_istream(std::move(bodyString)), length, contentType); + } + else + { + web::http::uri_builder formData; + for (auto& kvp : formParams) + { + formData.append_query(kvp.first, kvp.second); + } + request.set_body(formData.query(), U("application/x-www-form-urlencoded")); + } + } - web::http::uri_builder builder(path); - for (auto& kvp : queryParams) - { - builder.append_query(kvp.first, kvp.second); - } - request.set_request_uri(builder.to_uri()); - request.set_method(method); - if ( !request.headers().has( web::http::header_names::user_agent ) ) - { - request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); - } + web::http::uri_builder builder(path); + for (auto& kvp : queryParams) + { + builder.append_query(kvp.first, kvp.second); + } + request.set_request_uri(builder.to_uri()); + request.set_method(method); + if ( !request.headers().has( web::http::header_names::user_agent ) ) + { + request.headers().add( web::http::header_names::user_agent, m_Configuration->getUserAgent() ); + } - return client.request(request); + return client.request(request); } } diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 5e7ed98350e..81b38cb09c5 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * ApiClient.h - * - * This is an API client responsible for stating the HTTP calls + * + * This is an API client responsible for stating the HTTP calls */ #ifndef ApiClient_H_ @@ -25,8 +25,8 @@ #include "IHttpBody.h" #include "HttpContent.h" -#include -#include +#include +#include #include #include @@ -43,39 +43,39 @@ class ApiClient public: ApiClient( std::shared_ptr configuration = nullptr ); virtual ~ApiClient(); - + std::shared_ptr getConfiguration() const; void setConfiguration(std::shared_ptr configuration); - + static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); - + template static utility::string_t parameterToArrayString(std::vector value) { utility::stringstream_t ss; - + for( size_t i = 0; i < value.size(); i++) { if( i > 0) ss << U(", "); ss << ApiClient::parameterToString(value[i]); } - return ss.str(); + return ss.str(); } - - pplx::task callApi( - const utility::string_t& path, - const utility::string_t& method, - const std::map& queryParams, - const std::shared_ptr postBody, - const std::map& headerParams, - const std::map& formParams, + + pplx::task callApi( + const utility::string_t& path, + const utility::string_t& method, + const std::map& queryParams, + const std::shared_ptr postBody, + const std::map& headerParams, + const std::map& formParams, const std::map>& fileParams, const utility::string_t& contentType ) const; - + protected: std::shared_ptr m_Configuration; diff --git a/samples/client/petstore/cpprest/ApiConfiguration.cpp b/samples/client/petstore/cpprest/ApiConfiguration.cpp index ddbc1bc3eb2..1520a56d347 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.cpp +++ b/samples/client/petstore/cpprest/ApiConfiguration.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiConfiguration.h b/samples/client/petstore/cpprest/ApiConfiguration.h index 290f1fc7edf..0574783f690 100644 --- a/samples/client/petstore/cpprest/ApiConfiguration.h +++ b/samples/client/petstore/cpprest/ApiConfiguration.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * ApiConfiguration.h - * - * This class represents a single item of a multipart-formdata request. + * + * This class represents a single item of a multipart-formdata request. */ #ifndef ApiConfiguration_H_ @@ -23,7 +23,7 @@ #include -#include +#include #include namespace io { namespace swagger { @@ -35,18 +35,18 @@ class ApiConfiguration public: ApiConfiguration(); virtual ~ApiConfiguration(); - + web::http::client::http_client_config& getHttpConfig(); void setHttpConfig( web::http::client::http_client_config& value ); - + utility::string_t getBaseUrl() const; void setBaseUrl( const utility::string_t value ); - + utility::string_t getUserAgent() const; void setUserAgent( const utility::string_t value ); - + std::map& getDefaultHeaders(); - + utility::string_t getApiKey( const utility::string_t& prefix) const; void setApiKey( const utility::string_t& prefix, const utility::string_t& apiKey ); @@ -55,7 +55,7 @@ protected: std::map m_DefaultHeaders; std::map m_ApiKeys; web::http::client::http_client_config m_HttpConfig; - utility::string_t m_UserAgent; + utility::string_t m_UserAgent; }; } diff --git a/samples/client/petstore/cpprest/ApiException.cpp b/samples/client/petstore/cpprest/ApiException.cpp index 8e3646eb973..5ddf808f9f0 100644 --- a/samples/client/petstore/cpprest/ApiException.cpp +++ b/samples/client/petstore/cpprest/ApiException.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/ApiException.h b/samples/client/petstore/cpprest/ApiException.h index 96b1d03da00..835752ea75b 100644 --- a/samples/client/petstore/cpprest/ApiException.h +++ b/samples/client/petstore/cpprest/ApiException.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,7 +12,7 @@ /* * ApiException.h - * + * * This is the exception being thrown in case the api call was not successful */ @@ -21,7 +21,7 @@ -#include +#include #include #include @@ -45,12 +45,12 @@ public: , std::map& headers , std::shared_ptr content = nullptr ); virtual ~ApiException(); - + std::map& getHeaders(); std::shared_ptr getContent() const; - + protected: - std::shared_ptr m_Content; + std::shared_ptr m_Content; std::map m_Headers; }; diff --git a/samples/client/petstore/cpprest/HttpContent.cpp b/samples/client/petstore/cpprest/HttpContent.cpp index b6e9ff911c1..e9a619d7753 100644 --- a/samples/client/petstore/cpprest/HttpContent.cpp +++ b/samples/client/petstore/cpprest/HttpContent.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git diff --git a/samples/client/petstore/cpprest/HttpContent.h b/samples/client/petstore/cpprest/HttpContent.h index 9bcee47cc41..6b7bae0a5f7 100644 --- a/samples/client/petstore/cpprest/HttpContent.h +++ b/samples/client/petstore/cpprest/HttpContent.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * HttpContent.h - * - * This class represents a single item of a multipart-formdata request. + * + * This class represents a single item of a multipart-formdata request. */ #ifndef HttpContent_H_ @@ -23,7 +23,7 @@ #include -#include +#include namespace io { namespace swagger { @@ -50,7 +50,7 @@ public: virtual std::shared_ptr getData(); virtual void setData( std::shared_ptr value ); - + virtual void writeTo( std::ostream& stream ); protected: diff --git a/samples/client/petstore/cpprest/IHttpBody.h b/samples/client/petstore/cpprest/IHttpBody.h index 336ae2e98d2..0ccf80876e9 100644 --- a/samples/client/petstore/cpprest/IHttpBody.h +++ b/samples/client/petstore/cpprest/IHttpBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * IHttpBody.h - * - * This is the interface for contents that can be sent to a remote HTTP server. + * + * This is the interface for contents that can be sent to a remote HTTP server. */ #ifndef IHttpBody_H_ diff --git a/samples/client/petstore/cpprest/JsonBody.cpp b/samples/client/petstore/cpprest/JsonBody.cpp index 4586cb8c055..41ce32702c3 100644 --- a/samples/client/petstore/cpprest/JsonBody.cpp +++ b/samples/client/petstore/cpprest/JsonBody.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -19,7 +19,7 @@ namespace model { JsonBody::JsonBody( const web::json::value& json) : m_Json(json) -{ +{ } JsonBody::~JsonBody() diff --git a/samples/client/petstore/cpprest/JsonBody.h b/samples/client/petstore/cpprest/JsonBody.h index d9c0f1598cc..335be0a72b6 100644 --- a/samples/client/petstore/cpprest/JsonBody.h +++ b/samples/client/petstore/cpprest/JsonBody.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * JsonBody.h - * - * This is a JSON http body which can be submitted via http + * + * This is a JSON http body which can be submitted via http */ #ifndef JsonBody_H_ @@ -22,7 +22,7 @@ #include "IHttpBody.h" -#include +#include namespace io { namespace swagger { @@ -37,7 +37,7 @@ public: virtual ~JsonBody(); void writeTo( std::ostream& target ) override; - + protected: web::json::value m_Json; }; diff --git a/samples/client/petstore/cpprest/ModelBase.cpp b/samples/client/petstore/cpprest/ModelBase.cpp index 399e1a49c31..f97fe013cd5 100644 --- a/samples/client/petstore/cpprest/ModelBase.cpp +++ b/samples/client/petstore/cpprest/ModelBase.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -26,7 +26,7 @@ ModelBase::~ModelBase() web::json::value ModelBase::toJson( const utility::string_t& value ) { - return web::json::value::string(value); + return web::json::value::string(value); } web::json::value ModelBase::toJson( const utility::datetime& value ) { @@ -38,7 +38,7 @@ web::json::value ModelBase::toJson( int32_t value ) } web::json::value ModelBase::toJson( int64_t value ) { - return web::json::value::number(value); + return web::json::value::number(value); } web::json::value ModelBase::toJson( double value ) { @@ -58,7 +58,7 @@ web::json::value ModelBase::toJson( std::shared_ptr content ) std::shared_ptr ModelBase::fileFromJson(web::json::value& val) { std::shared_ptr content(new HttpContent); - + if(val.has_field(U("ContentDisposition"))) { content->setContentDisposition( ModelBase::stringFromJson(val[U("ContentDisposition")]) ); @@ -181,14 +181,14 @@ utility::string_t ModelBase::toBase64( std::shared_ptr value ) { case 1: value->read( read, 1 ); - temp = read[0] << 16; + temp = read[0] << 16; base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); base64.append( 2, Base64PadChar ); break; case 2: value->read( read, 2 ); - temp = read[0] << 16; + temp = read[0] << 16; temp += read[1] << 8; base64.append( 1, Base64Chars[(temp & 0x00FC0000) >> 18] ); base64.append( 1, Base64Chars[(temp & 0x0003F000) >> 12] ); @@ -203,7 +203,7 @@ utility::string_t ModelBase::toBase64( std::shared_ptr value ) std::shared_ptr ModelBase::fromBase64( const utility::string_t& encoded ) { std::shared_ptr result(new std::stringstream); - + char outBuf[3] = { 0 }; uint32_t temp = 0; @@ -213,9 +213,9 @@ std::shared_ptr ModelBase::fromBase64( const utility::string_t& en for ( size_t quantumPosition = 0; quantumPosition < 4; quantumPosition++ ) { temp <<= 6; - if ( *cursor >= 0x41 && *cursor <= 0x5A ) + if ( *cursor >= 0x41 && *cursor <= 0x5A ) { - temp |= *cursor - 0x41; + temp |= *cursor - 0x41; } else if ( *cursor >= 0x61 && *cursor <= 0x7A ) { @@ -295,7 +295,7 @@ double ModelBase::doubleFromJson(web::json::value& val) int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); int64_t result = 0; ss >> result; @@ -304,7 +304,7 @@ int64_t ModelBase::int64_tFromHttpContent(std::shared_ptr val) int32_t ModelBase::int32_tFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); int32_t result = 0; ss >> result; @@ -314,22 +314,22 @@ utility::string_t ModelBase::stringFromHttpContent(std::shared_ptr { std::shared_ptr data = val->getData(); data->seekg( 0, data->beg ); - + std::string str((std::istreambuf_iterator(*data.get())), std::istreambuf_iterator()); - + return utility::conversions::to_string_t(str); } utility::datetime ModelBase::dateFromHttpContent(std::shared_ptr val) { - utility::string_t str = ModelBase::stringFromHttpContent(val); + utility::string_t str = ModelBase::stringFromHttpContent(val); return utility::datetime::from_string(str, utility::datetime::ISO_8601); } bool ModelBase::boolFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); bool result = false; ss >> result; @@ -338,7 +338,7 @@ bool ModelBase::boolFromHttpContent(std::shared_ptr val) double ModelBase::doubleFromHttpContent(std::shared_ptr val) { utility::string_t str = ModelBase::stringFromHttpContent(val); - + utility::stringstream_t ss(str); double result = 0.0; ss >> result; diff --git a/samples/client/petstore/cpprest/ModelBase.h b/samples/client/petstore/cpprest/ModelBase.h index b2fb4f1118f..fa65266449f 100644 --- a/samples/client/petstore/cpprest/ModelBase.h +++ b/samples/client/petstore/cpprest/ModelBase.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,7 +12,7 @@ /* * ModelBase.h - * + * * This is the base class for all model classes */ @@ -24,7 +24,7 @@ #include "MultipartFormData.h" #include -#include +#include namespace io { namespace swagger { @@ -52,7 +52,7 @@ public: static web::json::value toJson( int32_t value ); static web::json::value toJson( int64_t value ); static web::json::value toJson( double value ); - + static int64_t int64_tFromJson(web::json::value& val); static int32_t int32_tFromJson(web::json::value& val); static utility::string_t stringFromJson(web::json::value& val); @@ -60,7 +60,7 @@ public: static double doubleFromJson(web::json::value& val); static bool boolFromJson(web::json::value& val); static std::shared_ptr fileFromJson(web::json::value& val); - + static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::string_t& value, const utility::string_t& contentType = U("")); static std::shared_ptr toHttpContent( const utility::string_t& name, const utility::datetime& value, const utility::string_t& contentType = U("")); static std::shared_ptr toHttpContent( const utility::string_t& name, std::shared_ptr value ); @@ -68,14 +68,14 @@ public: static std::shared_ptr toHttpContent( const utility::string_t& name, int32_t value, const utility::string_t& contentType = U("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, int64_t value, const utility::string_t& contentType = U("") ); static std::shared_ptr toHttpContent( const utility::string_t& name, double value, const utility::string_t& contentType = U("") ); - + static int64_t int64_tFromHttpContent(std::shared_ptr val); static int32_t int32_tFromHttpContent(std::shared_ptr val); static utility::string_t stringFromHttpContent(std::shared_ptr val); static utility::datetime dateFromHttpContent(std::shared_ptr val); static bool boolFromHttpContent(std::shared_ptr val); static double doubleFromHttpContent(std::shared_ptr val); - + static utility::string_t toBase64( utility::string_t value ); static utility::string_t toBase64( std::shared_ptr value ); diff --git a/samples/client/petstore/cpprest/MultipartFormData.cpp b/samples/client/petstore/cpprest/MultipartFormData.cpp index e0c6b54a0b8..a7e5f56c9f9 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.cpp +++ b/samples/client/petstore/cpprest/MultipartFormData.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -11,10 +11,10 @@ */ #include "MultipartFormData.h" -#include "ModelBase.h" +#include "ModelBase.h" #include -#include +#include namespace io { namespace swagger { @@ -94,7 +94,7 @@ void MultipartFormData::writeTo( std::ostream& target ) // body std::shared_ptr data = content->getData(); - + data->seekg( 0, data->end ); std::vector dataBytes( data->tellg() ); diff --git a/samples/client/petstore/cpprest/MultipartFormData.h b/samples/client/petstore/cpprest/MultipartFormData.h index 3f633c20958..63b84dcb3a9 100644 --- a/samples/client/petstore/cpprest/MultipartFormData.h +++ b/samples/client/petstore/cpprest/MultipartFormData.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * MultipartFormData.h - * - * This class represents a container for building a application/x-multipart-formdata requests. + * + * This class represents a container for building a application/x-multipart-formdata requests. */ #ifndef MultipartFormData_H_ @@ -48,7 +48,7 @@ public: virtual std::shared_ptr getContent(const utility::string_t& name) const; virtual bool hasContent(const utility::string_t& name) const; virtual void writeTo( std::ostream& target ); - + protected: std::vector> m_Contents; utility::string_t m_Boundary; diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index daff60c39a4..aa9aab9d89c 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -39,21 +39,27 @@ PetApi::~PetApi() pplx::task PetApi::addPet(std::shared_ptr body) { + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->addPet")); + } + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -64,7 +70,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -72,44 +78,37 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->addPet does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; consumeHttpContentTypes.insert( U("application/json") ); -consumeHttpContentTypes.insert( U("application/xml") ); - - + consumeHttpContentTypes.insert( U("application/xml") ); + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - + json = ModelBase::toJson(body); - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - - if(body.get()) + if(body.get()) { body->toMultipart(multipart, U("body")); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -118,19 +117,19 @@ consumeHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("PetApi->addPet does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -139,7 +138,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , U("error calling addPet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -151,33 +150,33 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task PetApi::deletePet(int64_t petId, utility::string_t apiKey) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/{petId}"); boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -188,7 +187,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -196,55 +195,47 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->deletePet does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + { headerParams[U("api_key")] = ApiClient::parameterToString(apiKey); - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->deletePet does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -253,7 +244,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling deletePet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -265,32 +256,32 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task>> PetApi::findPetsByStatus(std::vector status) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/findByStatus"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -301,7 +292,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -309,51 +300,47 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->findPetsByStatus does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - + { queryParams[U("status")] = ApiClient::parameterToArrayString(status); - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->findPetsByStatus does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -362,7 +349,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling findPetsByStatus: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -374,58 +361,57 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::vector> result; - - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + for( auto& item : json.as_array() ) { std::shared_ptr itemObj(new Pet()); itemObj->fromJson(item); - result.push_back(itemObj); + result.push_back(itemObj); } } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task>> PetApi::findPetsByTags(std::vector tags) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/findByTags"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -436,7 +422,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -444,51 +430,47 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->findPetsByTags does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - + { queryParams[U("tags")] = ApiClient::parameterToArrayString(tags); - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->findPetsByTags does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -497,7 +479,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling findPetsByTags: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -509,59 +491,58 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::vector> result; - - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + for( auto& item : json.as_array() ) { std::shared_ptr itemObj(new Pet()); itemObj->fromJson(item); - result.push_back(itemObj); + result.push_back(itemObj); } } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task> PetApi::getPetById(int64_t petId) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/{petId}"); boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -572,7 +553,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -580,43 +561,34 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->getPetById does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->getPetById does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - // authentication (petstore_auth) required - // oauth2 authentication is added automatically as part of the http_client_config + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (api_key) required { utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); @@ -625,13 +597,13 @@ responseHttpContentTypes.insert( U("application/xml") ); headerParams[U("api_key")] = apiKey; } } - + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -640,7 +612,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling getPetById: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -652,50 +624,56 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::shared_ptr result(new Pet()); - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + result->fromJson(json); } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task PetApi::updatePet(std::shared_ptr body) { + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling PetApi->updatePet")); + } + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -706,7 +684,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -714,44 +692,37 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->updatePet does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; consumeHttpContentTypes.insert( U("application/json") ); -consumeHttpContentTypes.insert( U("application/xml") ); - - + consumeHttpContentTypes.insert( U("application/xml") ); + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - + json = ModelBase::toJson(body); - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - - if(body.get()) + if(body.get()) { body->toMultipart(multipart, U("body")); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -760,19 +731,19 @@ consumeHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("PetApi->updatePet does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -781,7 +752,7 @@ consumeHttpContentTypes.insert( U("application/xml") ); , U("error calling updatePet: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -793,33 +764,33 @@ consumeHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } -pplx::task PetApi::updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status) +pplx::task PetApi::updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/{petId}"); boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -830,7 +801,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -838,61 +809,52 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->updatePetWithForm does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; consumeHttpContentTypes.insert( U("application/x-www-form-urlencoded") ); - - - { - - } + { formParams[ U("name") ] = ApiClient::parameterToString(name); - } { formParams[ U("status") ] = ApiClient::parameterToString(status); - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->updatePetWithForm does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -901,7 +863,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling updatePetWithForm: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -913,22 +875,22 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } -pplx::task PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) +pplx::task> PetApi::uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/pet/{petId}/uploadImage"); boost::replace_all(path, U("{") U("petId") U("}"), ApiClient::parameterToString(petId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; @@ -936,10 +898,9 @@ pplx::task PetApi::uploadFile(int64_t petId, utility::string_t additionalM std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -950,7 +911,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -958,61 +919,52 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("PetApi->uploadFile does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; consumeHttpContentTypes.insert( U("multipart/form-data") ); - - - { - - } + { formParams[ U("additionalMetadata") ] = ApiClient::parameterToString(additionalMetadata); - } if (file != nullptr) { fileParams[ U("file") ] = file; - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("PetApi->uploadFile does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (petstore_auth) required // oauth2 authentication is added automatically as part of the http_client_config - + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -1021,7 +973,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling uploadFile: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -1033,13 +985,31 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { - return void(); - }); + std::shared_ptr result(new ApiResponse()); + + if(responseHttpContentType == U("application/json")) + { + web::json::value json = web::json::value::parse(response); + + result->fromJson(json); + } + // else if(responseHttpContentType == U("multipart/form-data")) + // { + // TODO multipart response parsing + // } + else + { + throw ApiException(500 + , U("error calling findPetsByStatus: unsupported response type")); + } + + return result; + }); } } diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index b0714fef286..d60c3c80fca 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,16 +12,17 @@ /* * PetApi.h - * + * * */ - + #ifndef PetApi_H_ #define PetApi_H_ #include "ApiClient.h" +#include "ApiResponse.h" #include "HttpContent.h" #include "Pet.h" #include @@ -44,7 +45,7 @@ public: /// /// /// - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store pplx::task addPet(std::shared_ptr body); /// /// Deletes a pet @@ -60,7 +61,7 @@ public: /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter (optional, default to available) + /// Status values that need to be considered for filter pplx::task>> findPetsByStatus(std::vector status); /// /// Finds Pets by tags @@ -68,15 +69,15 @@ public: /// /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// - /// Tags to filter by (optional) + /// Tags to filter by pplx::task>> findPetsByTags(std::vector tags); /// /// Find pet by ID /// /// - /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// Returns a single pet /// - /// ID of pet that needs to be fetched + /// ID of pet to return pplx::task> getPetById(int64_t petId); /// /// Update an existing pet @@ -84,7 +85,7 @@ public: /// /// /// - /// Pet object that needs to be added to the store (optional) + /// Pet object that needs to be added to the store pplx::task updatePet(std::shared_ptr body); /// /// Updates a pet in the store with form data @@ -93,7 +94,7 @@ public: /// /// /// ID of pet that needs to be updated/// Updated name of the pet (optional)/// Updated status of the pet (optional) - pplx::task updatePetWithForm(utility::string_t petId, utility::string_t name, utility::string_t status); + pplx::task updatePetWithForm(int64_t petId, utility::string_t name, utility::string_t status); /// /// uploads an image /// @@ -101,12 +102,12 @@ public: /// /// /// ID of pet to update/// Additional data to pass to server (optional)/// file to upload (optional) - pplx::task uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); - + pplx::task> uploadFile(int64_t petId, utility::string_t additionalMetadata, std::shared_ptr file); + protected: - std::shared_ptr m_ApiClient; + std::shared_ptr m_ApiClient; }; - + } } } diff --git a/samples/client/petstore/cpprest/api/StoreApi.cpp b/samples/client/petstore/cpprest/api/StoreApi.cpp index 83187645cc4..39a3c6a39f7 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.cpp +++ b/samples/client/petstore/cpprest/api/StoreApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -39,22 +39,22 @@ StoreApi::~StoreApi() pplx::task StoreApi::deleteOrder(utility::string_t orderId) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order/{orderId}"); boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -65,7 +65,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -73,48 +73,41 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("StoreApi->deleteOrder does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("StoreApi->deleteOrder does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -123,7 +116,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling deleteOrder: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -135,21 +128,21 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task> StoreApi::getInventory() { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/inventory"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; @@ -157,10 +150,9 @@ pplx::task> StoreApi::getInventory() std::unordered_set responseHttpContentTypes; responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -171,7 +163,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -179,37 +171,34 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("StoreApi->getInventory does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("StoreApi->getInventory does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + // authentication (api_key) required { utility::string_t apiKey = apiConfiguration->getApiKey(U("api_key")); @@ -218,13 +207,13 @@ responseHttpContentTypes.insert( U("application/xml") ); headerParams[U("api_key")] = apiKey; } } - + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -233,7 +222,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling getInventory: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -245,57 +234,56 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::map result; - - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + for( auto& item : json.as_object() ) { result[item.first] = ModelBase::int32_tFromJson(item.second); - } + } } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } -pplx::task> StoreApi::getOrderById(utility::string_t orderId) +pplx::task> StoreApi::getOrderById(int64_t orderId) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order/{orderId}"); boost::replace_all(path, U("{") U("orderId") U("}"), ApiClient::parameterToString(orderId)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -306,7 +294,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -314,48 +302,41 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("StoreApi->getOrderById does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("StoreApi->getOrderById does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -364,7 +345,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling getOrderById: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -376,50 +357,56 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::shared_ptr result(new Order()); - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + result->fromJson(json); } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task> StoreApi::placeOrder(std::shared_ptr body) { + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling StoreApi->placeOrder")); + } + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/store/order"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -430,7 +417,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -438,42 +425,35 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("StoreApi->placeOrder does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - + json = ModelBase::toJson(body); - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - - if(body.get()) + if(body.get()) { body->toMultipart(multipart, U("body")); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -482,17 +462,17 @@ responseHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("StoreApi->placeOrder does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -501,7 +481,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling placeOrder: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -513,31 +493,31 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::shared_ptr result(new Order()); - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + result->fromJson(json); } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } } diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 96632ea40b0..60ec088b326 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,10 +12,10 @@ /* * StoreApi.h - * + * * */ - + #ifndef StoreApi_H_ #define StoreApi_H_ @@ -61,20 +61,20 @@ public: /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - pplx::task> getOrderById(utility::string_t orderId); + pplx::task> getOrderById(int64_t orderId); /// /// Place an order for a pet /// /// /// /// - /// order placed for purchasing the pet (optional) + /// order placed for purchasing the pet pplx::task> placeOrder(std::shared_ptr body); - + protected: - std::shared_ptr m_ApiClient; + std::shared_ptr m_ApiClient; }; - + } } } diff --git a/samples/client/petstore/cpprest/api/UserApi.cpp b/samples/client/petstore/cpprest/api/UserApi.cpp index 32f1c51d1fb..669be733361 100644 --- a/samples/client/petstore/cpprest/api/UserApi.cpp +++ b/samples/client/petstore/cpprest/api/UserApi.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -39,21 +39,27 @@ UserApi::~UserApi() pplx::task UserApi::createUser(std::shared_ptr body) { + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->createUser")); + } + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -64,7 +70,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -72,42 +78,35 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->createUser does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - + json = ModelBase::toJson(body); - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - - if(body.get()) + if(body.get()) { body->toMultipart(multipart, U("body")); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -116,17 +115,17 @@ responseHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("UserApi->createUser does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -135,7 +134,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling createUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -147,32 +146,32 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task UserApi::createUsersWithArrayInput(std::vector> body) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/createWithArray"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -183,7 +182,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -191,25 +190,22 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->createUsersWithArrayInput does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - - + { std::vector jsonArray; for( auto& item : body ) @@ -219,18 +215,14 @@ responseHttpContentTypes.insert( U("application/xml") ); } json = web::json::value::array(jsonArray); } - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - { std::vector jsonArray; for( auto& item : body ) @@ -240,7 +232,6 @@ responseHttpContentTypes.insert( U("application/xml") ); } multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -249,17 +240,17 @@ responseHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("UserApi->createUsersWithArrayInput does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -268,7 +259,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling createUsersWithArrayInput: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -280,32 +271,32 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task UserApi::createUsersWithListInput(std::vector> body) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/createWithList"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -316,7 +307,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -324,25 +315,22 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->createUsersWithListInput does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - - + { std::vector jsonArray; for( auto& item : body ) @@ -352,18 +340,14 @@ responseHttpContentTypes.insert( U("application/xml") ); } json = web::json::value::array(jsonArray); } - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - { std::vector jsonArray; for( auto& item : body ) @@ -373,7 +357,6 @@ responseHttpContentTypes.insert( U("application/xml") ); } multipart->add(ModelBase::toHttpContent(U("body"), web::json::value::array(jsonArray), U("application/json"))); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -382,17 +365,17 @@ responseHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("UserApi->createUsersWithListInput does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("POST"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -401,7 +384,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling createUsersWithListInput: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -413,33 +396,33 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task UserApi::deleteUser(utility::string_t username) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -450,7 +433,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -458,48 +441,41 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->deleteUser does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("UserApi->deleteUser does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("DELETE"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -508,7 +484,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling deleteUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -520,33 +496,33 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task> UserApi::getUserByName(utility::string_t username) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -557,7 +533,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -565,48 +541,41 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->getUserByName does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("UserApi->getUserByName does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -615,7 +584,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling getUserByName: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -627,50 +596,50 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { std::shared_ptr result(new User()); - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + result->fromJson(json); } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task UserApi::loginUser(utility::string_t username, utility::string_t password) { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/login"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -681,12 +650,12 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); } - // plain text + // plain text else if( responseHttpContentTypes.find(U("text/plain")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("text/plain"); @@ -694,54 +663,49 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->loginUser does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - + { queryParams[U("username")] = ApiClient::parameterToString(username); - } { queryParams[U("password")] = ApiClient::parameterToString(password); - } - std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("UserApi->loginUser does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -750,7 +714,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling loginUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -762,17 +726,17 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { utility::string_t result(U("")); - + if(responseHttpContentType == U("application/json")) { web::json::value json = web::json::value::parse(response); - + result = ModelBase::stringFromJson(json); } @@ -782,35 +746,35 @@ responseHttpContentTypes.insert( U("application/xml") ); } // else if(responseHttpContentType == U("multipart/form-data")) // { - // TODO multipart response parsing + // TODO multipart response parsing // } - else + else { throw ApiException(500 , U("error calling findPetsByStatus: unsupported response type")); } - + return result; - }); + }); } pplx::task UserApi::logoutUser() { - + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/logout"); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -821,7 +785,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -829,44 +793,41 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->logoutUser does not produce any supported media type")); - } - + } + headerParams[U("Accept")] = responseHttpContentType; - + std::unordered_set consumeHttpContentTypes; - - + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - } else { throw ApiException(415, U("UserApi->logoutUser does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("GET"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -875,7 +836,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling logoutUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -887,33 +848,39 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } pplx::task UserApi::updateUser(utility::string_t username, std::shared_ptr body) { + // verify the required parameter 'body' is set + if (body == nullptr) + { + throw ApiException(400, U("Missing required parameter 'body' when calling UserApi->updateUser")); + } + std::shared_ptr apiConfiguration( m_ApiClient->getConfiguration() ); utility::string_t path = U("/user/{username}"); boost::replace_all(path, U("{") U("username") U("}"), ApiClient::parameterToString(username)); - + std::map queryParams; std::map headerParams( apiConfiguration->getDefaultHeaders() ); std::map formParams; std::map> fileParams; std::unordered_set responseHttpContentTypes; + responseHttpContentTypes.insert( U("application/xml") ); responseHttpContentTypes.insert( U("application/json") ); -responseHttpContentTypes.insert( U("application/xml") ); - + utility::string_t responseHttpContentType; - + // use JSON if possible if ( responseHttpContentTypes.size() == 0 ) { @@ -924,7 +891,7 @@ responseHttpContentTypes.insert( U("application/xml") ); { responseHttpContentType = U("application/json"); } - // multipart formdata + // multipart formdata else if( responseHttpContentTypes.find(U("multipart/form-data")) != responseHttpContentTypes.end() ) { responseHttpContentType = U("multipart/form-data"); @@ -932,46 +899,35 @@ responseHttpContentTypes.insert( U("application/xml") ); else { throw ApiException(400, U("UserApi->updateUser does not produce any supported media type")); - } - - headerParams[U("Accept")] = responseHttpContentType; - - std::unordered_set consumeHttpContentTypes; - - - { - } - + + headerParams[U("Accept")] = responseHttpContentType; + + std::unordered_set consumeHttpContentTypes; + std::shared_ptr httpBody; utility::string_t requestHttpContentType; - + // use JSON if possible if ( consumeHttpContentTypes.size() == 0 || consumeHttpContentTypes.find(U("application/json")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("application/json"); - web::json::value json; - + json = ModelBase::toJson(body); - - + httpBody = std::shared_ptr( new JsonBody( json ) ); - } - // multipart formdata + // multipart formdata else if( consumeHttpContentTypes.find(U("multipart/form-data")) != consumeHttpContentTypes.end() ) { requestHttpContentType = U("multipart/form-data"); - std::shared_ptr multipart(new MultipartFormData); - - if(body.get()) + if(body.get()) { body->toMultipart(multipart, U("body")); } - httpBody = multipart; requestHttpContentType += U("; boundary=") + multipart->getBoundary(); @@ -980,17 +936,17 @@ responseHttpContentTypes.insert( U("application/xml") ); { throw ApiException(415, U("UserApi->updateUser does not consume any supported media type")); } - - //Set the request content type in the header. - headerParams[U("Content-Type")] = requestHttpContentType; - - + + //Set the request content type in the header. + headerParams[U("Content-Type")] = requestHttpContentType; + + return m_ApiClient->callApi(path, U("PUT"), queryParams, httpBody, headerParams, formParams, fileParams, requestHttpContentType) .then([=](web::http::http_response response) { // 1xx - informational : OK // 2xx - successful : OK - // 3xx - redirection : OK + // 3xx - redirection : OK // 4xx - client error : not OK // 5xx - client error : not OK if (response.status_code() >= 400) @@ -999,7 +955,7 @@ responseHttpContentTypes.insert( U("application/xml") ); , U("error calling updateUser: ") + response.reason_phrase() , std::make_shared(response.extract_utf8string(true).get())); } - + // check response content type if(response.headers().has(U("Content-Type"))) { @@ -1011,13 +967,13 @@ responseHttpContentTypes.insert( U("application/xml") ); , std::make_shared(response.extract_utf8string(true).get())); } } - + return response.extract_string(); }) .then([=](utility::string_t response) { return void(); - }); + }); } } diff --git a/samples/client/petstore/cpprest/api/UserApi.h b/samples/client/petstore/cpprest/api/UserApi.h index 530d70aba0f..e94de1a1241 100644 --- a/samples/client/petstore/cpprest/api/UserApi.h +++ b/samples/client/petstore/cpprest/api/UserApi.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,10 +12,10 @@ /* * UserApi.h - * + * * */ - + #ifndef UserApi_H_ #define UserApi_H_ @@ -44,7 +44,7 @@ public: /// /// This can only be done by the logged in user. /// - /// Created user object (optional) + /// Created user object pplx::task createUser(std::shared_ptr body); /// /// Creates list of users with given input array @@ -52,7 +52,7 @@ public: /// /// /// - /// List of user object (optional) + /// List of user object pplx::task createUsersWithArrayInput(std::vector> body); /// /// Creates list of users with given input array @@ -60,7 +60,7 @@ public: /// /// /// - /// List of user object (optional) + /// List of user object pplx::task createUsersWithListInput(std::vector> body); /// /// Delete user @@ -84,7 +84,7 @@ public: /// /// /// - /// The user name for login (optional)/// The password for login in clear text (optional) + /// The user name for login/// The password for login in clear text pplx::task loginUser(utility::string_t username, utility::string_t password); /// /// Logs out current logged in user session @@ -100,13 +100,13 @@ public: /// /// This can only be done by the logged in user. /// - /// name that need to be deleted/// Updated user object (optional) + /// name that need to be deleted/// Updated user object pplx::task updateUser(utility::string_t username, std::shared_ptr body); - + protected: - std::shared_ptr m_ApiClient; + std::shared_ptr m_ApiClient; }; - + } } } diff --git a/samples/client/petstore/cpprest/git_push.sh b/samples/client/petstore/cpprest/git_push.sh index 970522bca1f..35d20f1851d 100644 --- a/samples/client/petstore/cpprest/git_push.sh +++ b/samples/client/petstore/cpprest/git_push.sh @@ -28,7 +28,7 @@ git init # Adds the files in the local repository and stages them for commit. git add . -# Commits the tracked changes and prepares them to be pushed to a remote repository. +# Commits the tracked changes and prepares them to be pushed to a remote repository. git commit -m "$release_note" # Sets the new remote diff --git a/samples/client/petstore/cpprest/model/ApiResponse.cpp b/samples/client/petstore/cpprest/model/ApiResponse.cpp index 44c0e720b7f..45bf13d1910 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.cpp +++ b/samples/client/petstore/cpprest/model/ApiResponse.cpp @@ -34,7 +34,7 @@ ApiResponse::~ApiResponse() { } -void ApiResponse::validate() +void ApiResponse::validate() { // TODO: implement validation } @@ -42,7 +42,7 @@ void ApiResponse::validate() web::json::value ApiResponse::toJson() const { web::json::value val = web::json::value::object(); - + if(m_CodeIsSet) { val[U("code")] = ModelBase::toJson(m_Code); @@ -69,12 +69,12 @@ void ApiResponse::fromJson(web::json::value& val) if(val.has_field(U("type"))) { setType(ModelBase::stringFromJson(val[U("type")])); - + } if(val.has_field(U("message"))) { setMessage(ModelBase::stringFromJson(val[U("message")])); - + } } @@ -94,12 +94,12 @@ void ApiResponse::toMultipart(std::shared_ptr multipart, cons if(m_TypeIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("type"), m_Type)); - + } if(m_MessageIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("message"), m_Message)); - + } } @@ -119,17 +119,17 @@ void ApiResponse::fromMultiPart(std::shared_ptr multipart, co if(multipart->hasContent(U("type"))) { setType(ModelBase::stringFromHttpContent(multipart->getContent(U("type")))); - + } if(multipart->hasContent(U("message"))) { setMessage(ModelBase::stringFromHttpContent(multipart->getContent(U("message")))); - + } } - - + + int32_t ApiResponse::getCode() const { return m_Code; @@ -143,7 +143,7 @@ bool ApiResponse::codeIsSet() const { return m_CodeIsSet; } -void ApiResponse::unsetCode() +void ApiResponse::unsetCode() { m_CodeIsSet = false; } @@ -160,7 +160,7 @@ bool ApiResponse::typeIsSet() const { return m_TypeIsSet; } -void ApiResponse::unsetType() +void ApiResponse::unsetType() { m_TypeIsSet = false; } @@ -177,7 +177,7 @@ bool ApiResponse::messageIsSet() const { return m_MessageIsSet; } -void ApiResponse::unsetMessage() +void ApiResponse::unsetMessage() { m_MessageIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/ApiResponse.h b/samples/client/petstore/cpprest/model/ApiResponse.h index 7bdefe4afba..49945e5fd71 100644 --- a/samples/client/petstore/cpprest/model/ApiResponse.h +++ b/samples/client/petstore/cpprest/model/ApiResponse.h @@ -12,7 +12,7 @@ /* * ApiResponse.h - * + * * Describes the result of uploading an image resource */ @@ -33,15 +33,15 @@ namespace model { /// Describes the result of uploading an image resource /// class ApiResponse - : public ModelBase + : public ModelBase { public: ApiResponse(); virtual ~ApiResponse(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -49,10 +49,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// ApiResponse members - + + ///////////////////////////////////////////// + /// ApiResponse members + /// /// /// @@ -74,7 +74,7 @@ public: void setMessage(utility::string_t value); bool messageIsSet() const; void unsetMessage(); - + protected: int32_t m_Code; bool m_CodeIsSet; diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index 6350dc0a72e..bdb6d8e894a 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -32,7 +32,7 @@ Category::~Category() { } -void Category::validate() +void Category::validate() { // TODO: implement validation } @@ -40,7 +40,7 @@ void Category::validate() web::json::value Category::toJson() const { web::json::value val = web::json::value::object(); - + if(m_IdIsSet) { val[U("id")] = ModelBase::toJson(m_Id); @@ -63,7 +63,7 @@ void Category::fromJson(web::json::value& val) if(val.has_field(U("name"))) { setName(ModelBase::stringFromJson(val[U("name")])); - + } } @@ -83,7 +83,7 @@ void Category::toMultipart(std::shared_ptr multipart, const u if(m_NameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); - + } } @@ -103,12 +103,12 @@ void Category::fromMultiPart(std::shared_ptr multipart, const if(multipart->hasContent(U("name"))) { setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); - + } } - - + + int64_t Category::getId() const { return m_Id; @@ -122,7 +122,7 @@ bool Category::idIsSet() const { return m_IdIsSet; } -void Category::unsetId() +void Category::unsetId() { m_IdIsSet = false; } @@ -139,7 +139,7 @@ bool Category::nameIsSet() const { return m_NameIsSet; } -void Category::unsetName() +void Category::unsetName() { m_NameIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/Category.h b/samples/client/petstore/cpprest/model/Category.h index d3ef9b99b48..80e759424a9 100644 --- a/samples/client/petstore/cpprest/model/Category.h +++ b/samples/client/petstore/cpprest/model/Category.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * Category.h - * - * + * + * A category for a pet */ #ifndef Category_H_ @@ -30,18 +30,18 @@ namespace client { namespace model { /// -/// +/// A category for a pet /// class Category - : public ModelBase + : public ModelBase { public: Category(); virtual ~Category(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -49,10 +49,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// Category members - + + ///////////////////////////////////////////// + /// Category members + /// /// /// @@ -67,7 +67,7 @@ public: void setName(utility::string_t value); bool nameIsSet() const; void unsetName(); - + protected: int64_t m_Id; bool m_IdIsSet; diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index 87aa74ed5f0..e21d867cd7e 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -40,7 +40,7 @@ Order::~Order() { } -void Order::validate() +void Order::validate() { // TODO: implement validation } @@ -48,7 +48,7 @@ void Order::validate() web::json::value Order::toJson() const { web::json::value val = web::json::value::object(); - + if(m_IdIsSet) { val[U("id")] = ModelBase::toJson(m_Id); @@ -95,12 +95,12 @@ void Order::fromJson(web::json::value& val) if(val.has_field(U("shipDate"))) { setShipDate(ModelBase::dateFromJson(val[U("shipDate")])); - + } if(val.has_field(U("status"))) { setStatus(ModelBase::stringFromJson(val[U("status")])); - + } if(val.has_field(U("complete"))) { @@ -132,12 +132,12 @@ void Order::toMultipart(std::shared_ptr multipart, const util if(m_ShipDateIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("shipDate"), m_ShipDate)); - + } if(m_StatusIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); - + } if(m_CompleteIsSet) { @@ -169,12 +169,12 @@ void Order::fromMultiPart(std::shared_ptr multipart, const ut if(multipart->hasContent(U("shipDate"))) { setShipDate(ModelBase::dateFromHttpContent(multipart->getContent(U("shipDate")))); - + } if(multipart->hasContent(U("status"))) { setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); - + } if(multipart->hasContent(U("complete"))) { @@ -182,8 +182,8 @@ void Order::fromMultiPart(std::shared_ptr multipart, const ut } } - - + + int64_t Order::getId() const { return m_Id; @@ -197,7 +197,7 @@ bool Order::idIsSet() const { return m_IdIsSet; } -void Order::unsetId() +void Order::unsetId() { m_IdIsSet = false; } @@ -214,7 +214,7 @@ bool Order::petIdIsSet() const { return m_PetIdIsSet; } -void Order::unsetPetId() +void Order::unsetPetId() { m_PetIdIsSet = false; } @@ -231,7 +231,7 @@ bool Order::quantityIsSet() const { return m_QuantityIsSet; } -void Order::unsetQuantity() +void Order::unsetQuantity() { m_QuantityIsSet = false; } @@ -248,7 +248,7 @@ bool Order::shipDateIsSet() const { return m_ShipDateIsSet; } -void Order::unsetShipDate() +void Order::unsetShipDate() { m_ShipDateIsSet = false; } @@ -265,7 +265,7 @@ bool Order::statusIsSet() const { return m_StatusIsSet; } -void Order::unsetStatus() +void Order::unsetStatus() { m_StatusIsSet = false; } @@ -282,7 +282,7 @@ bool Order::completeIsSet() const { return m_CompleteIsSet; } -void Order::unsetComplete() +void Order::unsetComplete() { m_CompleteIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/Order.h b/samples/client/petstore/cpprest/model/Order.h index 2728a17c29a..b8f22de9f47 100644 --- a/samples/client/petstore/cpprest/model/Order.h +++ b/samples/client/petstore/cpprest/model/Order.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * Order.h - * - * + * + * An order for a pets from the pet store */ #ifndef Order_H_ @@ -30,18 +30,18 @@ namespace client { namespace model { /// -/// +/// An order for a pets from the pet store /// class Order - : public ModelBase + : public ModelBase { public: Order(); virtual ~Order(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -49,10 +49,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// Order members - + + ///////////////////////////////////////////// + /// Order members + /// /// /// @@ -95,7 +95,7 @@ public: void setComplete(bool value); bool completeIsSet() const; void unsetComplete(); - + protected: int64_t m_Id; bool m_IdIsSet; diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 47d4528e01e..51dd6d883e9 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -35,7 +35,7 @@ Pet::~Pet() { } -void Pet::validate() +void Pet::validate() { // TODO: implement validation } @@ -43,7 +43,7 @@ void Pet::validate() web::json::value Pet::toJson() const { web::json::value val = web::json::value::object(); - + if(m_IdIsSet) { val[U("id")] = ModelBase::toJson(m_Id); @@ -68,7 +68,7 @@ web::json::value Pet::toJson() const jsonArray.push_back(ModelBase::toJson(item)); } - if(jsonArray.size() > 0) + if(jsonArray.size() > 0) { val[U("tags")] = web::json::value::array(jsonArray); } @@ -90,13 +90,13 @@ void Pet::fromJson(web::json::value& val) } if(val.has_field(U("category"))) { - if(!val[U("category")].is_null()) + if(!val[U("category")].is_null()) { std::shared_ptr newItem(new Category()); newItem->fromJson(val[U("category")]); setCategory( newItem ); } - + } setName(ModelBase::stringFromJson(val[U("name")])); { @@ -116,7 +116,7 @@ void Pet::fromJson(web::json::value& val) for( auto& item : val[U("tags")].as_array() ) { - if(item.is_null()) + if(item.is_null()) { m_Tags.push_back( std::shared_ptr(nullptr) ); } @@ -133,7 +133,7 @@ void Pet::fromJson(web::json::value& val) if(val.has_field(U("status"))) { setStatus(ModelBase::stringFromJson(val[U("status")])); - + } } @@ -156,7 +156,7 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit { m_Category->toMultipart(multipart, U("category.")); } - + } multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); { @@ -174,7 +174,7 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit jsonArray.push_back(ModelBase::toJson(item)); } - if(jsonArray.size() > 0) + if(jsonArray.size() > 0) { multipart->add(ModelBase::toHttpContent(namePrefix + U("tags"), web::json::value::array(jsonArray), U("application/json"))); } @@ -182,7 +182,7 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit if(m_StatusIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("status"), m_Status)); - + } } @@ -207,12 +207,12 @@ void Pet::fromMultiPart(std::shared_ptr multipart, const util newItem->fromMultiPart(multipart, U("category.")); setCategory( newItem ); } - + } setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); { m_PhotoUrls.clear(); - + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("photoUrls")))); for( auto& item : jsonArray.as_array() ) { @@ -223,13 +223,13 @@ void Pet::fromMultiPart(std::shared_ptr multipart, const util { m_Tags.clear(); if(multipart->hasContent(U("tags"))) - { - + { + web::json::value jsonArray = web::json::value::parse(ModelBase::stringFromHttpContent(multipart->getContent(U("tags")))); for( auto& item : jsonArray.as_array() ) { - if(item.is_null()) + if(item.is_null()) { m_Tags.push_back( std::shared_ptr(nullptr) ); } @@ -246,12 +246,12 @@ void Pet::fromMultiPart(std::shared_ptr multipart, const util if(multipart->hasContent(U("status"))) { setStatus(ModelBase::stringFromHttpContent(multipart->getContent(U("status")))); - + } } - - + + int64_t Pet::getId() const { return m_Id; @@ -265,7 +265,7 @@ bool Pet::idIsSet() const { return m_IdIsSet; } -void Pet::unsetId() +void Pet::unsetId() { m_IdIsSet = false; } @@ -282,7 +282,7 @@ bool Pet::categoryIsSet() const { return m_CategoryIsSet; } -void Pet::unsetCategory() +void Pet::unsetCategory() { m_CategoryIsSet = false; } @@ -307,7 +307,7 @@ bool Pet::tagsIsSet() const { return m_TagsIsSet; } -void Pet::unsetTags() +void Pet::unsetTags() { m_TagsIsSet = false; } @@ -324,7 +324,7 @@ bool Pet::statusIsSet() const { return m_StatusIsSet; } -void Pet::unsetStatus() +void Pet::unsetStatus() { m_StatusIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index d9411f3797a..91704dc9ed7 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * Pet.h - * - * + * + * A pet for sale in the pet store */ #ifndef Pet_H_ @@ -22,10 +22,10 @@ #include "ModelBase.h" -#include "Tag.h" -#include #include "Category.h" +#include #include +#include "Tag.h" namespace io { namespace swagger { @@ -33,18 +33,18 @@ namespace client { namespace model { /// -/// +/// A pet for sale in the pet store /// class Pet - : public ModelBase + : public ModelBase { public: Pet(); virtual ~Pet(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -52,10 +52,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// Pet members - + + ///////////////////////////////////////////// + /// Pet members + /// /// /// @@ -92,7 +92,7 @@ public: void setStatus(utility::string_t value); bool statusIsSet() const; void unsetStatus(); - + protected: int64_t m_Id; bool m_IdIsSet; diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 22fba97c0b9..3cb0798c99e 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -32,7 +32,7 @@ Tag::~Tag() { } -void Tag::validate() +void Tag::validate() { // TODO: implement validation } @@ -40,7 +40,7 @@ void Tag::validate() web::json::value Tag::toJson() const { web::json::value val = web::json::value::object(); - + if(m_IdIsSet) { val[U("id")] = ModelBase::toJson(m_Id); @@ -63,7 +63,7 @@ void Tag::fromJson(web::json::value& val) if(val.has_field(U("name"))) { setName(ModelBase::stringFromJson(val[U("name")])); - + } } @@ -83,7 +83,7 @@ void Tag::toMultipart(std::shared_ptr multipart, const utilit if(m_NameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("name"), m_Name)); - + } } @@ -103,12 +103,12 @@ void Tag::fromMultiPart(std::shared_ptr multipart, const util if(multipart->hasContent(U("name"))) { setName(ModelBase::stringFromHttpContent(multipart->getContent(U("name")))); - + } } - - + + int64_t Tag::getId() const { return m_Id; @@ -122,7 +122,7 @@ bool Tag::idIsSet() const { return m_IdIsSet; } -void Tag::unsetId() +void Tag::unsetId() { m_IdIsSet = false; } @@ -139,7 +139,7 @@ bool Tag::nameIsSet() const { return m_NameIsSet; } -void Tag::unsetName() +void Tag::unsetName() { m_NameIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/Tag.h b/samples/client/petstore/cpprest/model/Tag.h index 40edb4f1ee9..a977ca07980 100644 --- a/samples/client/petstore/cpprest/model/Tag.h +++ b/samples/client/petstore/cpprest/model/Tag.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * Tag.h - * - * + * + * A tag for a pet */ #ifndef Tag_H_ @@ -30,18 +30,18 @@ namespace client { namespace model { /// -/// +/// A tag for a pet /// class Tag - : public ModelBase + : public ModelBase { public: Tag(); virtual ~Tag(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -49,10 +49,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// Tag members - + + ///////////////////////////////////////////// + /// Tag members + /// /// /// @@ -67,7 +67,7 @@ public: void setName(utility::string_t value); bool nameIsSet() const; void unsetName(); - + protected: int64_t m_Id; bool m_IdIsSet; diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index fa19cbe64c3..1ea09f35b50 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -44,7 +44,7 @@ User::~User() { } -void User::validate() +void User::validate() { // TODO: implement validation } @@ -52,7 +52,7 @@ void User::validate() web::json::value User::toJson() const { web::json::value val = web::json::value::object(); - + if(m_IdIsSet) { val[U("id")] = ModelBase::toJson(m_Id); @@ -99,32 +99,32 @@ void User::fromJson(web::json::value& val) if(val.has_field(U("username"))) { setUsername(ModelBase::stringFromJson(val[U("username")])); - + } if(val.has_field(U("firstName"))) { setFirstName(ModelBase::stringFromJson(val[U("firstName")])); - + } if(val.has_field(U("lastName"))) { setLastName(ModelBase::stringFromJson(val[U("lastName")])); - + } if(val.has_field(U("email"))) { setEmail(ModelBase::stringFromJson(val[U("email")])); - + } if(val.has_field(U("password"))) { setPassword(ModelBase::stringFromJson(val[U("password")])); - + } if(val.has_field(U("phone"))) { setPhone(ModelBase::stringFromJson(val[U("phone")])); - + } if(val.has_field(U("userStatus"))) { @@ -148,32 +148,32 @@ void User::toMultipart(std::shared_ptr multipart, const utili if(m_UsernameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("username"), m_Username)); - + } if(m_FirstNameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("firstName"), m_FirstName)); - + } if(m_LastNameIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("lastName"), m_LastName)); - + } if(m_EmailIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("email"), m_Email)); - + } if(m_PasswordIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("password"), m_Password)); - + } if(m_PhoneIsSet) { multipart->add(ModelBase::toHttpContent(namePrefix + U("phone"), m_Phone)); - + } if(m_UserStatusIsSet) { @@ -197,32 +197,32 @@ void User::fromMultiPart(std::shared_ptr multipart, const uti if(multipart->hasContent(U("username"))) { setUsername(ModelBase::stringFromHttpContent(multipart->getContent(U("username")))); - + } if(multipart->hasContent(U("firstName"))) { setFirstName(ModelBase::stringFromHttpContent(multipart->getContent(U("firstName")))); - + } if(multipart->hasContent(U("lastName"))) { setLastName(ModelBase::stringFromHttpContent(multipart->getContent(U("lastName")))); - + } if(multipart->hasContent(U("email"))) { setEmail(ModelBase::stringFromHttpContent(multipart->getContent(U("email")))); - + } if(multipart->hasContent(U("password"))) { setPassword(ModelBase::stringFromHttpContent(multipart->getContent(U("password")))); - + } if(multipart->hasContent(U("phone"))) { setPhone(ModelBase::stringFromHttpContent(multipart->getContent(U("phone")))); - + } if(multipart->hasContent(U("userStatus"))) { @@ -230,8 +230,8 @@ void User::fromMultiPart(std::shared_ptr multipart, const uti } } - - + + int64_t User::getId() const { return m_Id; @@ -245,7 +245,7 @@ bool User::idIsSet() const { return m_IdIsSet; } -void User::unsetId() +void User::unsetId() { m_IdIsSet = false; } @@ -262,7 +262,7 @@ bool User::usernameIsSet() const { return m_UsernameIsSet; } -void User::unsetUsername() +void User::unsetUsername() { m_UsernameIsSet = false; } @@ -279,7 +279,7 @@ bool User::firstNameIsSet() const { return m_FirstNameIsSet; } -void User::unsetFirstName() +void User::unsetFirstName() { m_FirstNameIsSet = false; } @@ -296,7 +296,7 @@ bool User::lastNameIsSet() const { return m_LastNameIsSet; } -void User::unsetLastName() +void User::unsetLastName() { m_LastNameIsSet = false; } @@ -313,7 +313,7 @@ bool User::emailIsSet() const { return m_EmailIsSet; } -void User::unsetEmail() +void User::unsetEmail() { m_EmailIsSet = false; } @@ -330,7 +330,7 @@ bool User::passwordIsSet() const { return m_PasswordIsSet; } -void User::unsetPassword() +void User::unsetPassword() { m_PasswordIsSet = false; } @@ -347,7 +347,7 @@ bool User::phoneIsSet() const { return m_PhoneIsSet; } -void User::unsetPhone() +void User::unsetPhone() { m_PhoneIsSet = false; } @@ -364,7 +364,7 @@ bool User::userStatusIsSet() const { return m_UserStatusIsSet; } -void User::unsetUserStatus() +void User::unsetUserStatus() { m_UserStatusIsSet = false; } diff --git a/samples/client/petstore/cpprest/model/User.h b/samples/client/petstore/cpprest/model/User.h index 58def69adde..83b2120a360 100644 --- a/samples/client/petstore/cpprest/model/User.h +++ b/samples/client/petstore/cpprest/model/User.h @@ -1,9 +1,9 @@ /** * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -12,8 +12,8 @@ /* * User.h - * - * + * + * A User who is purchasing from the pet store */ #ifndef User_H_ @@ -30,18 +30,18 @@ namespace client { namespace model { /// -/// +/// A User who is purchasing from the pet store /// class User - : public ModelBase + : public ModelBase { public: User(); virtual ~User(); - ///////////////////////////////////////////// - /// ModelBase overrides - + ///////////////////////////////////////////// + /// ModelBase overrides + void validate() override; web::json::value toJson() const override; @@ -49,10 +49,10 @@ public: void toMultipart(std::shared_ptr multipart, const utility::string_t& namePrefix) const override; void fromMultiPart(std::shared_ptr multipart, const utility::string_t& namePrefix) override; - - ///////////////////////////////////////////// - /// User members - + + ///////////////////////////////////////////// + /// User members + /// /// /// @@ -109,7 +109,7 @@ public: void setUserStatus(int32_t value); bool userStatusIsSet() const; void unsetUserStatus(); - + protected: int64_t m_Id; bool m_IdIsSet; From e55664cdc99c7f135b46ead31c12dfbc49b24f96 Mon Sep 17 00:00:00 2001 From: Dan Wilson Date: Tue, 13 Dec 2016 02:13:06 -0600 Subject: [PATCH 163/269] Remove invalid code from mustache for arrays. (#4266) Rewrite ParameterToString to handle other slice types other than just string. --- .../src/main/resources/go/api.mustache | 11 +++----- .../src/main/resources/go/api_client.mustache | 27 ++++++++++--------- .../client/petstore/go/go-petstore/README.md | 2 ++ .../petstore/go/go-petstore/api_client.go | 27 ++++++++++--------- .../petstore/go/go-petstore/class_model.go | 17 ++++++++++++ .../go/go-petstore/docs/ClassModel.md | 10 +++++++ .../petstore/go/go-petstore/docs/EnumTest.md | 1 + .../petstore/go/go-petstore/docs/FakeApi.md | 2 +- .../petstore/go/go-petstore/docs/OuterEnum.md | 9 +++++++ .../petstore/go/go-petstore/docs/PetApi.md | 2 +- .../petstore/go/go-petstore/docs/StoreApi.md | 2 +- .../petstore/go/go-petstore/docs/UserApi.md | 2 +- .../petstore/go/go-petstore/enum_test.go | 2 ++ .../petstore/go/go-petstore/fake_api.go | 13 +++------ .../petstore/go/go-petstore/outer_enum.go | 14 ++++++++++ .../client/petstore/go/go-petstore/pet_api.go | 18 +++---------- .../petstore/go/go-petstore/user_api.go | 4 +-- 17 files changed, 102 insertions(+), 61 deletions(-) create mode 100644 samples/client/petstore/go/go-petstore/class_model.go create mode 100644 samples/client/petstore/go/go-petstore/docs/ClassModel.md create mode 100644 samples/client/petstore/go/go-petstore/docs/OuterEnum.md create mode 100644 samples/client/petstore/go/go-petstore/outer_enum.go diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index 186fe556c06..33f11a0bde1 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -83,16 +83,11 @@ func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType} {{#queryParams}} {{#isListContainer}} var collectionFormat = "{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}" - if collectionFormat == "multi" { - for _, value := range {{paramName}} { - localVarQueryParams.Add("{{baseName}}", value) - } - } else { - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) - } + localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, collectionFormat)) + {{/isListContainer}} {{^isListContainer}} - localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) + localVarQueryParams.Add("{{baseName}}", a.Configuration.APIClient.ParameterToString({{paramName}}, "")) {{/isListContainer}} {{/queryParams}} {{/hasQueryParams}} diff --git a/modules/swagger-codegen/src/main/resources/go/api_client.mustache b/modules/swagger-codegen/src/main/resources/go/api_client.mustache index a92c7631202..e4ae2d09904 100644 --- a/modules/swagger-codegen/src/main/resources/go/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api_client.mustache @@ -79,18 +79,21 @@ func (c *APIClient) CallAPI(path string, method string, return nil, fmt.Errorf("invalid method %v", method) } -func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string { - if reflect.TypeOf(obj).String() == "[]string" { - switch collectionFormat { - case "pipes": - return strings.Join(obj.([]string), "|") - case "ssv": - return strings.Join(obj.([]string), " ") - case "tsv": - return strings.Join(obj.([]string), "\t") - case "csv" : - return strings.Join(obj.([]string), ",") - } +func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { + delimiter := "" + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 164eaf91c07..1f00e75f05f 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -56,6 +56,7 @@ Class | Method | HTTP request | Description - [ArrayTest](docs/ArrayTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) - [Client](docs/Client.md) - [Dog](docs/Dog.md) - [EnumArrays](docs/EnumArrays.md) @@ -72,6 +73,7 @@ Class | Method | HTTP request | Description - [Name](docs/Name.md) - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) + - [OuterEnum](docs/OuterEnum.md) - [Pet](docs/Pet.md) - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) diff --git a/samples/client/petstore/go/go-petstore/api_client.go b/samples/client/petstore/go/go-petstore/api_client.go index d2cdab388eb..a93f346e102 100644 --- a/samples/client/petstore/go/go-petstore/api_client.go +++ b/samples/client/petstore/go/go-petstore/api_client.go @@ -88,18 +88,21 @@ func (c *APIClient) CallAPI(path string, method string, return nil, fmt.Errorf("invalid method %v", method) } -func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string { - if reflect.TypeOf(obj).String() == "[]string" { - switch collectionFormat { - case "pipes": - return strings.Join(obj.([]string), "|") - case "ssv": - return strings.Join(obj.([]string), " ") - case "tsv": - return strings.Join(obj.([]string), "\t") - case "csv" : - return strings.Join(obj.([]string), ",") - } +func (c *APIClient) ParameterToString(obj interface{}, collectionFormat string) string { + delimiter := "" + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") } return fmt.Sprintf("%v", obj) diff --git a/samples/client/petstore/go/go-petstore/class_model.go b/samples/client/petstore/go/go-petstore/class_model.go new file mode 100644 index 00000000000..efcd6540b20 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/class_model.go @@ -0,0 +1,17 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package petstore + +// Model for testing model with \"_class\" property +type ClassModel struct { + + Class string `json:"_class,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/docs/ClassModel.md b/samples/client/petstore/go/go-petstore/docs/ClassModel.md new file mode 100644 index 00000000000..d9005f21a01 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Class** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/EnumTest.md b/samples/client/petstore/go/go-petstore/docs/EnumTest.md index fe6ca0cb32d..2e67672188e 100644 --- a/samples/client/petstore/go/go-petstore/docs/EnumTest.md +++ b/samples/client/petstore/go/go-petstore/docs/EnumTest.md @@ -6,6 +6,7 @@ Name | Type | Description | Notes **EnumString** | **string** | | [optional] [default to null] **EnumInteger** | **int32** | | [optional] [default to null] **EnumNumber** | **float64** | | [optional] [default to null] +**OuterEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/go/go-petstore/docs/FakeApi.md b/samples/client/petstore/go/go-petstore/docs/FakeApi.md index ce6a7292d33..915750589e4 100644 --- a/samples/client/petstore/go/go-petstore/docs/FakeApi.md +++ b/samples/client/petstore/go/go-petstore/docs/FakeApi.md @@ -1,6 +1,6 @@ # \FakeApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to ** Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/go/go-petstore/docs/OuterEnum.md b/samples/client/petstore/go/go-petstore/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/go/go-petstore/docs/PetApi.md b/samples/client/petstore/go/go-petstore/docs/PetApi.md index e96bdc1a15e..2bccb81cd2b 100644 --- a/samples/client/petstore/go/go-petstore/docs/PetApi.md +++ b/samples/client/petstore/go/go-petstore/docs/PetApi.md @@ -1,6 +1,6 @@ # \PetApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to ** Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/go/go-petstore/docs/StoreApi.md b/samples/client/petstore/go/go-petstore/docs/StoreApi.md index 1ee858d2e30..83841e3f350 100644 --- a/samples/client/petstore/go/go-petstore/docs/StoreApi.md +++ b/samples/client/petstore/go/go-petstore/docs/StoreApi.md @@ -1,6 +1,6 @@ # \StoreApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to ** Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/go/go-petstore/docs/UserApi.md b/samples/client/petstore/go/go-petstore/docs/UserApi.md index 4950105ca86..88b825bb148 100644 --- a/samples/client/petstore/go/go-petstore/docs/UserApi.md +++ b/samples/client/petstore/go/go-petstore/docs/UserApi.md @@ -1,6 +1,6 @@ # \UserApi -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to ** Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/go/go-petstore/enum_test.go b/samples/client/petstore/go/go-petstore/enum_test.go index b76c647878f..086c239379b 100644 --- a/samples/client/petstore/go/go-petstore/enum_test.go +++ b/samples/client/petstore/go/go-petstore/enum_test.go @@ -17,4 +17,6 @@ type EnumTest struct { EnumInteger int32 `json:"enum_integer,omitempty"` EnumNumber float64 `json:"enum_number,omitempty"` + + OuterEnum OuterEnum `json:"outerEnum,omitempty"` } diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go index 49f9d8b7022..2170fe29f08 100644 --- a/samples/client/petstore/go/go-petstore/fake_api.go +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -219,15 +219,10 @@ func (a FakeApi) TestEnumParameters(enumFormStringArray []string, enumFormString localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } var collectionFormat = "csv" - if collectionFormat == "multi" { - for _, value := range enumQueryStringArray { - localVarQueryParams.Add("enum_query_string_array", value) - } - } else { - localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(enumQueryStringArray, collectionFormat)) - } - localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(enumQueryString, "")) - localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(enumQueryInteger, "")) + localVarQueryParams.Add("enum_query_string_array", a.Configuration.APIClient.ParameterToString(enumQueryStringArray, collectionFormat)) + + localVarQueryParams.Add("enum_query_string", a.Configuration.APIClient.ParameterToString(enumQueryString, "")) + localVarQueryParams.Add("enum_query_integer", a.Configuration.APIClient.ParameterToString(enumQueryInteger, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ "*/*", } diff --git a/samples/client/petstore/go/go-petstore/outer_enum.go b/samples/client/petstore/go/go-petstore/outer_enum.go new file mode 100644 index 00000000000..45cb3276ad1 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/outer_enum.go @@ -0,0 +1,14 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package petstore + +type OuterEnum struct { +} diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index 1bb9e596654..6e2f9d24f4b 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -202,13 +202,8 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } var collectionFormat = "csv" - if collectionFormat == "multi" { - for _, value := range status { - localVarQueryParams.Add("status", value) - } - } else { - localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) - } + localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) + // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -276,13 +271,8 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } var collectionFormat = "csv" - if collectionFormat == "multi" { - for _, value := range tags { - localVarQueryParams.Add("tags", value) - } - } else { - localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) - } + localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) + // to determine the Content-Type header localVarHttpContentTypes := []string{ } diff --git a/samples/client/petstore/go/go-petstore/user_api.go b/samples/client/petstore/go/go-petstore/user_api.go index 25e1f359ae1..2f574a8182c 100644 --- a/samples/client/petstore/go/go-petstore/user_api.go +++ b/samples/client/petstore/go/go-petstore/user_api.go @@ -366,8 +366,8 @@ func (a UserApi) LoginUser(username string, password string) (*string, *APIRespo for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - localVarQueryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) - localVarQueryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) + localVarQueryParams.Add("username", a.Configuration.APIClient.ParameterToString(username, "")) + localVarQueryParams.Add("password", a.Configuration.APIClient.ParameterToString(password, "")) // to determine the Content-Type header localVarHttpContentTypes := []string{ } From b33d4ec30c78bf4bfb4f51cb0b12e5c124359ba1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 13 Dec 2016 17:54:23 +0800 Subject: [PATCH 164/269] add enum_outer_doc.mustache for android (#4381) --- .../src/main/resources/android/enum_outer_doc.mustache | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/android/enum_outer_doc.mustache diff --git a/modules/swagger-codegen/src/main/resources/android/enum_outer_doc.mustache b/modules/swagger-codegen/src/main/resources/android/enum_outer_doc.mustache new file mode 100644 index 00000000000..20c512aaeae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/enum_outer_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} From a291d3113aa729efb20226262c6bc2fe3a864d5a Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 14 Dec 2016 00:40:21 +0800 Subject: [PATCH 165/269] [Android] better code format for Android (volley) API client (#4384) * better code format for android volley * better code format for apiinvoker, add docstring * use 2-space indentation for pair class * use 2 spaces indentation for other classes in android --- .../languages/AndroidClientCodegen.java | 1 - .../android/libraries/volley/Pair.mustache | 50 +- .../android/libraries/volley/api.mustache | 138 ++-- .../libraries/volley/apiException.mustache | 20 + .../libraries/volley/apiInvoker.mustache | 148 ++-- .../libraries/volley/auth/apikeyauth.mustache | 2 +- .../volley/auth/httpbasicauth.mustache | 38 +- .../libraries/volley/auth/oauth.mustache | 8 +- .../volley/request/deleterequest.mustache | 134 ++-- .../volley/request/patchrequest.mustache | 134 ++-- .../volley/request/postrequest.mustache | 134 ++-- .../volley/request/putrequest.mustache | 134 ++-- .../java/io/swagger/client/ApiException.java | 20 + .../java/io/swagger/client/ApiInvoker.java | 130 ++-- .../src/main/java/io/swagger/client/Pair.java | 50 +- .../java/io/swagger/client/api/PetApi.java | 733 ++++++++---------- .../java/io/swagger/client/api/StoreApi.java | 342 ++++---- .../java/io/swagger/client/api/UserApi.java | 679 ++++++++-------- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 38 +- .../swagger/client/request/DeleteRequest.java | 134 ++-- .../swagger/client/request/PatchRequest.java | 134 ++-- .../swagger/client/request/PostRequest.java | 134 ++-- .../io/swagger/client/request/PutRequest.java | 134 ++-- 24 files changed, 1688 insertions(+), 1783 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 5f08cebcdf9..4fb1660db46 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -390,7 +390,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); - LOGGER.info("CodegenConstants.SERIALIZABLE_MODEL = " + additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL)); //make api and model doc path available in mustache template additionalProperties.put( "apiDocPath", apiDocPath ); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache index 60e15c94ed4..442f9c7a811 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/Pair.mustache @@ -2,38 +2,38 @@ package {{invokerPackage}}; public class Pair { - private String name = ""; - private String value = ""; + private String name = ""; + private String value = ""; - public Pair(String name, String value) { - setName(name); - setValue(value); - } + public Pair(String name, String value) { + setName(name); + setValue(value); + } - private void setName(String name) { - if (!isValidString(name)) return; + private void setName(String name) { + if (!isValidString(name)) return; - this.name = name; - } + this.name = name; + } - private void setValue(String value) { - if (!isValidString(value)) return; + private void setValue(String value) { + if (!isValidString(value)) return; - this.value = value; - } + this.value = value; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; - return true; - } + return true; + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index 0d18ad5572e..288408ab26c 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -54,83 +54,89 @@ public class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { + Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}} + {{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { VolleyError error = new VolleyError("Missing the required parameter '{{paramName}}' when calling {{nickname}}", - new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}")); - } - {{/required}}{{/allParams}} + new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}")); + } + {{/required}} + {{/allParams}} - // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + // create path and map variables + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + {{#queryParams}} + queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/queryParams}} + {{#headerParams}} + headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{/headerParams}} + String[] contentTypes = { + {{#consumes}} + "{{{mediaType}}}"{{#hasMore}},{{/hasMore}} + {{/consumes}} + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - {{#queryParams}} - queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); - {{/queryParams}} - - {{#headerParams}} - headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); - {{/headerParams}} - - String[] contentTypes = { - {{#consumes}}"{{{mediaType}}}"{{#hasMore}},{{/hasMore}}{{/consumes}} - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - {{#formParams}}{{#notFile}} - if ({{paramName}} != null) { - localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); - } - {{/notFile}}{{#isFile}} - if ({{paramName}} != null) { - localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}}); - } - {{/isFile}}{{/formParams}} - + {{#formParams}} + {{^isFile}} + if ({{paramName}} != null) { + localVarBuilder.addTextBody("{{baseName}}", ApiInvoker.parameterToString({{paramName}}), ApiInvoker.TEXT_PLAIN_UTF8); + } + {{/isFile}} + {{#isFile}} + if ({{paramName}} != null) { + localVarBuilder.addBinaryBody("{{baseName}}", {{paramName}}); + } + {{/isFile}} + {{/formParams}} HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}}));{{/notFile}} - {{/formParams}} + {{#formParams}} + {{^isFile}} + formParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{/isFile}} + {{/formParams}} + } + + String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(localVarResponse, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; + } else { + return {{#returnType}}null{{/returnType}}; } - - String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(localVarResponse, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; - } else { - return {{#returnType}}null{{/returnType}}; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache index 8d9da2fbe5d..381af8fb4b0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiException.mustache @@ -12,18 +12,38 @@ public class ApiException extends Exception { this.message = message; } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ public int getCode() { return code; } + /** + * Set the HTTP status code. + * + * @param code HTTP status code. + */ public void setCode(int code) { this.code = code; } + /** + * Get the error message. + * + * @return Error message. + */ public String getMessage() { return message; } + /** + * Set the error messages. + * + * @param message Error message. + */ public void setMessage(String message) { this.message = message; } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache index d57d8bb058f..09e2b177fab 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/apiInvoker.mustache @@ -179,48 +179,48 @@ public class ApiInvoker { } public static void initializeInstance() { - initializeInstance(null); + initializeInstance(null); } public static void initializeInstance(Cache cache) { - initializeInstance(cache, null, 0, null, 30); + initializeInstance(cache, null, 0, null, 30); } public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { - INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); - setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}"); + INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); + setUserAgent("{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{artifactVersion}}}/android{{/httpUserAgent}}"); - // Setup authentications (key: authentication name, value: authentication). - INSTANCE.authentications = new HashMap(); - {{#authMethods}} - {{#isApiKey}} - INSTANCE.authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}")); - {{/isApiKey}} - {{#isBasic}} - INSTANCE.authentications.put("{{name}}", new HttpBasicAuth()); - {{/isBasic}} - {{#isOAuth}} - // TODO: comment out below as OAuth does not exist - //INSTANCE.authentications.put("{{name}}", new OAuth()); - {{/isOAuth}} - {{/authMethods}} - // Prevent the authentications from being modified. - INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); + // Setup authentications (key: authentication name, value: authentication). + INSTANCE.authentications = new HashMap(); + {{#authMethods}} + {{#isApiKey}} + INSTANCE.authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}")); + {{/isApiKey}} + {{#isBasic}} + INSTANCE.authentications.put("{{name}}", new HttpBasicAuth()); + {{/isBasic}} + {{#isOAuth}} + // TODO: comment out below as OAuth does not exist + //INSTANCE.authentications.put("{{name}}", new OAuth()); + {{/isOAuth}} + {{/authMethods}} + // Prevent the authentications from being modified. + INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); } private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { - if(cache == null) cache = new NoCache(); - if(network == null) { - HttpStack stack = new HurlStack(); - network = new BasicNetwork(stack); - } + if(cache == null) cache = new NoCache(); + if(network == null) { + HttpStack stack = new HurlStack(); + network = new BasicNetwork(stack); + } - if(delivery == null) { - initConnectionRequest(cache, network); - } else { - initConnectionRequest(cache, network, threadPoolSize, delivery); - } - this.connectionTimeout = connectionTimeout; + if(delivery == null) { + initConnectionRequest(cache, network); + } else { + initConnectionRequest(cache, network, threadPoolSize, delivery); + } + this.connectionTimeout = connectionTimeout; } public static ApiInvoker getInstance() { @@ -273,25 +273,25 @@ public class ApiInvoker { } /** - * Get authentications (key: authentication name, value: authentication). - */ + * Get authentications (key: authentication name, value: authentication). + */ public Map getAuthentications() { return authentications; } /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** - * Helper method to set username for the first HTTP basic authentication. - */ + * Helper method to set username for the first HTTP basic authentication. + */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { @@ -303,21 +303,21 @@ public class ApiInvoker { } /** - * Helper method to set password for the first HTTP basic authentication. - */ + * Helper method to set password for the first HTTP basic authentication. + */ public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); } /** - * Helper method to set API key value for the first API key authentication. - */ + * Helper method to set API key value for the first API key authentication. + */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { @@ -329,8 +329,8 @@ public class ApiInvoker { } /** - * Helper method to set API key prefix for the first API key authentication. - */ + * Helper method to set API key prefix for the first API key authentication. + */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { @@ -342,18 +342,18 @@ public class ApiInvoker { } public void setConnectionTimeout(int connectionTimeout){ - this.connectionTimeout = connectionTimeout; + this.connectionTimeout = connectionTimeout; } public int getConnectionTimeout() { - return connectionTimeout; + return connectionTimeout; } /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); @@ -363,17 +363,21 @@ public class ApiInvoker { } public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { - RequestFuture future = RequestFuture.newFuture(); - Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); - if(request != null) { - mRequestQueue.add(request); - return future.get(connectionTimeout, TimeUnit.SECONDS); - } else return "no data"; + RequestFuture future = RequestFuture.newFuture(); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); + if(request != null) { + mRequestQueue.add(request); + return future.get(connectionTimeout, TimeUnit.SECONDS); + } else { + return "no data"; + } } public void invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { - Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); - if (request != null) mRequestQueue.add(request); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); + if (request != null) { + mRequestQueue.add(request); + } } public Request createRequest(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { @@ -503,16 +507,16 @@ public class ApiInvoker { } private void initConnectionRequest(Cache cache, Network network) { - mRequestQueue = new RequestQueue(cache, network); - mRequestQueue.start(); + mRequestQueue = new RequestQueue(cache, network); + mRequestQueue.start(); } private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { - mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); - mRequestQueue.start(); + mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); + mRequestQueue.start(); } public void stopQueue() { - mRequestQueue.stop(); + mRequestQueue.stop(); } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache index 2208935ee42..9f5c6dcbaa2 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/apikeyauth.mustache @@ -46,7 +46,7 @@ public class ApiKeyAuth implements Authentication { public void applyToParams(List queryParams, Map headerParams) { String value; if (apiKey == null) { - return; + return; } if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache index 51017997ed4..f4f9a1a0bc0 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/httpbasicauth.mustache @@ -9,28 +9,28 @@ import java.util.Map; import java.util.List; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT)); - } + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT)); + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache index 72b5e0baab8..1839e96bf08 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/auth/oauth.mustache @@ -7,8 +7,8 @@ import java.util.Map; import java.util.List; public class OAuth implements Authentication { - @Override - public void applyToParams(List queryParams, Map headerParams) { - // TODO stub - } + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO stub + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache index 7dcc613d0f0..90956e791dc 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/deleterequest.mustache @@ -19,75 +19,75 @@ import java.util.Map; public class DeleteRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public DeleteRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.DELETE, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public DeleteRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.DELETE, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache index 5415ab602a2..b9a7fed6705 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/patchrequest.mustache @@ -19,75 +19,75 @@ import java.util.Map; public class PatchRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PatchRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.PATCH, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PatchRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PATCH, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache index 183fe15b9b5..2349b51a318 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/postrequest.mustache @@ -19,75 +19,75 @@ import java.util.Map; public class PostRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PostRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.POST, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PostRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.POST, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache index 88cf2edce8e..6773fb4da7f 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/request/putrequest.mustache @@ -19,75 +19,75 @@ import java.util.Map; public class PutRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PutRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.PUT, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PutRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PUT, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java index 60e7a3d92c9..7ccb9a47f48 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiException.java @@ -23,18 +23,38 @@ public class ApiException extends Exception { this.message = message; } + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ public int getCode() { return code; } + /** + * Set the HTTP status code. + * + * @param code HTTP status code. + */ public void setCode(int code) { this.code = code; } + /** + * Get the error message. + * + * @return Error message. + */ public String getMessage() { return message; } + /** + * Set the error messages. + * + * @param message Error message. + */ public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java index e9a7d1b1624..5791dbfd072 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/ApiInvoker.java @@ -190,39 +190,39 @@ public class ApiInvoker { } public static void initializeInstance() { - initializeInstance(null); + initializeInstance(null); } public static void initializeInstance(Cache cache) { - initializeInstance(cache, null, 0, null, 30); + initializeInstance(cache, null, 0, null, 30); } public static void initializeInstance(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { - INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); - setUserAgent("Swagger-Codegen/1.0.0/android"); + INSTANCE = new ApiInvoker(cache, network, threadPoolSize, delivery, connectionTimeout); + setUserAgent("Swagger-Codegen/1.0.0/android"); - // Setup authentications (key: authentication name, value: authentication). - INSTANCE.authentications = new HashMap(); - INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); - // TODO: comment out below as OAuth does not exist - //INSTANCE.authentications.put("petstore_auth", new OAuth()); - // Prevent the authentications from being modified. - INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); + // Setup authentications (key: authentication name, value: authentication). + INSTANCE.authentications = new HashMap(); + INSTANCE.authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // TODO: comment out below as OAuth does not exist + //INSTANCE.authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + INSTANCE.authentications = Collections.unmodifiableMap(INSTANCE.authentications); } private ApiInvoker(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery, int connectionTimeout) { - if(cache == null) cache = new NoCache(); - if(network == null) { - HttpStack stack = new HurlStack(); - network = new BasicNetwork(stack); - } + if(cache == null) cache = new NoCache(); + if(network == null) { + HttpStack stack = new HurlStack(); + network = new BasicNetwork(stack); + } - if(delivery == null) { - initConnectionRequest(cache, network); - } else { - initConnectionRequest(cache, network, threadPoolSize, delivery); - } - this.connectionTimeout = connectionTimeout; + if(delivery == null) { + initConnectionRequest(cache, network); + } else { + initConnectionRequest(cache, network, threadPoolSize, delivery); + } + this.connectionTimeout = connectionTimeout; } public static ApiInvoker getInstance() { @@ -275,25 +275,25 @@ public class ApiInvoker { } /** - * Get authentications (key: authentication name, value: authentication). - */ + * Get authentications (key: authentication name, value: authentication). + */ public Map getAuthentications() { return authentications; } /** - * Get authentication for the given name. - * - * @param authName The authentication name - * @return The authentication, null if not found - */ + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ public Authentication getAuthentication(String authName) { return authentications.get(authName); } /** - * Helper method to set username for the first HTTP basic authentication. - */ + * Helper method to set username for the first HTTP basic authentication. + */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBasicAuth) { @@ -305,21 +305,21 @@ public class ApiInvoker { } /** - * Helper method to set password for the first HTTP basic authentication. - */ + * Helper method to set password for the first HTTP basic authentication. + */ public void setPassword(String password) { - for (Authentication auth : authentications.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); } /** - * Helper method to set API key value for the first API key authentication. - */ + * Helper method to set API key value for the first API key authentication. + */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { @@ -331,8 +331,8 @@ public class ApiInvoker { } /** - * Helper method to set API key prefix for the first API key authentication. - */ + * Helper method to set API key prefix for the first API key authentication. + */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { if (auth instanceof ApiKeyAuth) { @@ -344,18 +344,18 @@ public class ApiInvoker { } public void setConnectionTimeout(int connectionTimeout){ - this.connectionTimeout = connectionTimeout; + this.connectionTimeout = connectionTimeout; } public int getConnectionTimeout() { - return connectionTimeout; + return connectionTimeout; } /** - * Update query and header parameters based on authentication settings. - * - * @param authNames The authentications to apply - */ + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); @@ -365,17 +365,21 @@ public class ApiInvoker { } public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException { - RequestFuture future = RequestFuture.newFuture(); - Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); - if(request != null) { - mRequestQueue.add(request); - return future.get(connectionTimeout, TimeUnit.SECONDS); - } else return "no data"; + RequestFuture future = RequestFuture.newFuture(); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future); + if(request != null) { + mRequestQueue.add(request); + return future.get(connectionTimeout, TimeUnit.SECONDS); + } else { + return "no data"; + } } public void invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { - Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); - if (request != null) mRequestQueue.add(request); + Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, stringRequest, errorListener); + if (request != null) { + mRequestQueue.add(request); + } } public Request createRequest(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames, Response.Listener stringRequest, Response.ErrorListener errorListener) throws ApiException { @@ -505,16 +509,16 @@ public class ApiInvoker { } private void initConnectionRequest(Cache cache, Network network) { - mRequestQueue = new RequestQueue(cache, network); - mRequestQueue.start(); + mRequestQueue = new RequestQueue(cache, network); + mRequestQueue.start(); } private void initConnectionRequest(Cache cache, Network network, int threadPoolSize, ResponseDelivery delivery) { - mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); - mRequestQueue.start(); + mRequestQueue = new RequestQueue(cache, network, threadPoolSize, delivery); + mRequestQueue.start(); } public void stopQueue() { - mRequestQueue.stop(); + mRequestQueue.stop(); } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java index d83f3053c71..df9d3f03908 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/Pair.java @@ -13,38 +13,38 @@ package io.swagger.client; public class Pair { - private String name = ""; - private String value = ""; + private String name = ""; + private String value = ""; - public Pair(String name, String value) { - setName(name); - setValue(value); - } + public Pair(String name, String value) { + setName(name); + setValue(value); + } - private void setName(String name) { - if (!isValidString(name)) return; + private void setName(String name) { + if (!isValidString(name)) return; - this.name = name; - } + this.name = name; + } - private void setValue(String value) { - if (!isValidString(value)) return; + private void setValue(String value) { + if (!isValidString(value)) return; - this.value = value; - } + this.value = value; + } - public String getName() { - return this.name; - } + public String getName() { + return this.name; + } - public String getValue() { - return this.value; - } + public String getValue() { + return this.value; + } - private boolean isValidString(String arg) { - if (arg == null) return false; - if (arg.trim().isEmpty()) return false; + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; - return true; - } + return true; + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java index 02291b27fd2..644a15c5da3 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/PetApi.java @@ -63,61 +63,56 @@ public class PetApi { * @return void */ public void addPet (Pet body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/json", + "application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -185,68 +180,60 @@ public class PetApi { * @return void */ public void deletePet (Long petId, String apiKey) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { + Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling deletePet", - new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); - } - + new ApiException(400, "Missing the required parameter 'petId' when calling deletePet")); + } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -320,62 +307,55 @@ public class PetApi { * @return List */ public List findPetsByStatus (List status) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - + Object postBody = null; - // create path and map variables - String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status)); - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (List) ApiInvoker.deserialize(localVarResponse, "array", Pet.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (List) ApiInvoker.deserialize(localVarResponse, "array", Pet.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -447,62 +427,55 @@ public class PetApi { * @return List */ public List findPetsByTags (List tags) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - + Object postBody = null; - // create path and map variables - String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags)); - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (List) ApiInvoker.deserialize(localVarResponse, "array", Pet.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (List) ApiInvoker.deserialize(localVarResponse, "array", Pet.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -574,67 +547,59 @@ public class PetApi { * @return Pet */ public Pet getPetById (Long petId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { + Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling getPetById", - new ApiException(400, "Missing the required parameter 'petId' when calling getPetById")); - } - + new ApiException(400, "Missing the required parameter 'petId' when calling getPetById")); + } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (Pet) ApiInvoker.deserialize(localVarResponse, "", Pet.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (Pet) ApiInvoker.deserialize(localVarResponse, "", Pet.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -711,61 +676,56 @@ public class PetApi { * @return void */ public void updatePet (Pet body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/json", + "application/xml" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - "application/json","application/xml" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -834,77 +794,68 @@ public class PetApi { * @return void */ public void updatePetWithForm (String petId, String name, String status) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { + Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling updatePetWithForm", - new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm")); - } - + new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm")); + } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - "application/x-www-form-urlencoded" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - if (name != null) { - localVarBuilder.addTextBody("name", ApiInvoker.parameterToString(name), ApiInvoker.TEXT_PLAIN_UTF8); - } - - if (status != null) { - localVarBuilder.addTextBody("status", ApiInvoker.parameterToString(status), ApiInvoker.TEXT_PLAIN_UTF8); - } - - + if (name != null) { + localVarBuilder.addTextBody("name", ApiInvoker.parameterToString(name), ApiInvoker.TEXT_PLAIN_UTF8); + } + if (status != null) { + localVarBuilder.addTextBody("status", ApiInvoker.parameterToString(status), ApiInvoker.TEXT_PLAIN_UTF8); + } HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - formParams.put("name", ApiInvoker.parameterToString(name)); -formParams.put("status", ApiInvoker.parameterToString(status)); + formParams.put("name", ApiInvoker.parameterToString(name)); + formParams.put("status", ApiInvoker.parameterToString(status)); + } + + String[] authNames = new String[] { "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -989,77 +940,67 @@ formParams.put("status", ApiInvoker.parameterToString(status)); * @return void */ public void uploadFile (Long petId, String additionalMetadata, File file) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'petId' is set - if (petId == null) { + Object postBody = null; + // verify the required parameter 'petId' is set + if (petId == null) { VolleyError error = new VolleyError("Missing the required parameter 'petId' when calling uploadFile", - new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile")); - } - + new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile")); + } - // create path and map variables - String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + "multipart/form-data" + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - "multipart/form-data" - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - if (additionalMetadata != null) { - localVarBuilder.addTextBody("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), ApiInvoker.TEXT_PLAIN_UTF8); - } - - if (file != null) { - localVarBuilder.addBinaryBody("file", file); - } - - + if (additionalMetadata != null) { + localVarBuilder.addTextBody("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata), ApiInvoker.TEXT_PLAIN_UTF8); + } + if (file != null) { + localVarBuilder.addBinaryBody("file", file); + } HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata)); + formParams.put("additionalMetadata", ApiInvoker.parameterToString(additionalMetadata)); + } + String[] authNames = new String[] { "petstore_auth" }; + + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } - - String[] authNames = new String[] { "petstore_auth" }; - - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); } - throw ex; - } catch (TimeoutException ex) { - throw ex; - } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java index bc3646d399a..1aac5e84fa5 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/StoreApi.java @@ -63,67 +63,59 @@ public class StoreApi { * @return void */ public void deleteOrder (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { + Object postBody = null; + // verify the required parameter 'orderId' is set + if (orderId == null) { VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling deleteOrder", - new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); - } - + new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder")); + } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -195,61 +187,54 @@ public class StoreApi { * @return Map */ public Map getInventory () throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - + Object postBody = null; - // create path and map variables - String path = "/store/inventory".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { "api_key" }; + String[] authNames = new String[] { "api_key" }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (Map) ApiInvoker.deserialize(localVarResponse, "map", Map.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (Map) ApiInvoker.deserialize(localVarResponse, "map", Map.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -320,67 +305,59 @@ public class StoreApi { * @return Order */ public Order getOrderById (String orderId) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'orderId' is set - if (orderId == null) { + Object postBody = null; + // verify the required parameter 'orderId' is set + if (orderId == null) { VolleyError error = new VolleyError("Missing the required parameter 'orderId' when calling getOrderById", - new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); - } - + new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById")); + } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -457,61 +434,54 @@ public class StoreApi { * @return Order */ public Order placeOrder (Order body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/store/order".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (Order) ApiInvoker.deserialize(localVarResponse, "", Order.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java index 9e9dcb6853c..0857956f749 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/api/UserApi.java @@ -63,61 +63,54 @@ public class UserApi { * @return void */ public void createUser (User body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/user".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -184,61 +177,54 @@ public class UserApi { * @return void */ public void createUsersWithArrayInput (List body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -305,61 +291,54 @@ public class UserApi { * @return void */ public void createUsersWithListInput (List body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - + Object postBody = body; - // create path and map variables - String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -426,67 +405,59 @@ public class UserApi { * @return void */ public void deleteUser (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { + Object postBody = null; + // verify the required parameter 'username' is set + if (username == null) { VolleyError error = new VolleyError("Missing the required parameter 'username' when calling deleteUser", - new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); - } - + new ApiException(400, "Missing the required parameter 'username' when calling deleteUser")); + } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -559,67 +530,59 @@ public class UserApi { * @return User */ public User getUserByName (String username) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - - // verify the required parameter 'username' is set - if (username == null) { + Object postBody = null; + // verify the required parameter 'username' is set + if (username == null) { VolleyError error = new VolleyError("Missing the required parameter 'username' when calling getUserByName", - new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); - } - + new ApiException(400, "Missing the required parameter 'username' when calling getUserByName")); + } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (User) ApiInvoker.deserialize(localVarResponse, "", User.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -697,63 +660,56 @@ public class UserApi { * @return String */ public String loginUser (String username, String password) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - + Object postBody = null; - // create path and map variables - String path = "/user/login".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + queryParams.addAll(ApiInvoker.parameterToPairs("", "username", username)); + queryParams.addAll(ApiInvoker.parameterToPairs("", "password", password)); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - queryParams.addAll(ApiInvoker.parameterToPairs("", "username", username)); - queryParams.addAll(ApiInvoker.parameterToPairs("", "password", password)); - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return (String) ApiInvoker.deserialize(localVarResponse, "", String.class); - } else { - return null; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return (String) ApiInvoker.deserialize(localVarResponse, "", String.class); + } else { + return null; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -825,61 +781,54 @@ public class UserApi { * @return void */ public void logoutUser () throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = null; - + Object postBody = null; - // create path and map variables - String path = "/user/logout".replaceAll("\\{format\\}","json"); + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** @@ -947,67 +896,59 @@ public class UserApi { * @return void */ public void updateUser (String username, User body) throws TimeoutException, ExecutionException, InterruptedException, ApiException { - Object postBody = body; - - // verify the required parameter 'username' is set - if (username == null) { + Object postBody = body; + // verify the required parameter 'username' is set + if (username == null) { VolleyError error = new VolleyError("Missing the required parameter 'username' when calling updateUser", - new ApiException(400, "Missing the required parameter 'username' when calling updateUser")); - } - + new ApiException(400, "Missing the required parameter 'username' when calling updateUser")); + } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - // query params - List queryParams = new ArrayList(); - // header params - Map headerParams = new HashMap(); - // form params - Map formParams = new HashMap(); + // query params + List queryParams = new ArrayList(); + // header params + Map headerParams = new HashMap(); + // form params + Map formParams = new HashMap(); + String[] contentTypes = { + }; + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - - String[] contentTypes = { - - }; - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if (contentType.startsWith("multipart/form-data")) { + if (contentType.startsWith("multipart/form-data")) { // file uploading MultipartEntityBuilder localVarBuilder = MultipartEntityBuilder.create(); - - HttpEntity httpEntity = localVarBuilder.build(); postBody = httpEntity; - } else { + } else { // normal form params - } + } - String[] authNames = new String[] { }; + String[] authNames = new String[] { }; - try { - String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); - if(localVarResponse != null){ - return ; - } else { - return ; - } - } catch (ApiException ex) { - throw ex; - } catch (InterruptedException ex) { - throw ex; - } catch (ExecutionException ex) { - if(ex.getCause() instanceof VolleyError) { - VolleyError volleyError = (VolleyError)ex.getCause(); - if (volleyError.networkResponse != null) { - throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); - } - } - throw ex; - } catch (TimeoutException ex) { - throw ex; + try { + String localVarResponse = apiInvoker.invokeAPI (basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); + if (localVarResponse != null) { + return ; + } else { + return ; } + } catch (ApiException ex) { + throw ex; + } catch (InterruptedException ex) { + throw ex; + } catch (ExecutionException ex) { + if (ex.getCause() instanceof VolleyError) { + VolleyError volleyError = (VolleyError)ex.getCause(); + if (volleyError.networkResponse != null) { + throw new ApiException(volleyError.networkResponse.statusCode, volleyError.getMessage()); + } + } + throw ex; + } catch (TimeoutException ex) { + throw ex; + } } /** diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ff48bc72ecd..58a3022c041 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -57,7 +57,7 @@ public class ApiKeyAuth implements Authentication { public void applyToParams(List queryParams, Map headerParams) { String value; if (apiKey == null) { - return; + return; } if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index aa2e467321a..21019099056 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -20,28 +20,28 @@ import java.util.Map; import java.util.List; public class HttpBasicAuth implements Authentication { - private String username; - private String password; + private String username; + private String password; - public String getUsername() { - return username; - } + public String getUsername() { + return username; + } - public void setUsername(String username) { - this.username = username; - } + public void setUsername(String username) { + this.username = username; + } - public String getPassword() { - return password; - } + public String getPassword() { + return password; + } - public void setPassword(String password) { - this.password = password; - } + public void setPassword(String password) { + this.password = password; + } - @Override - public void applyToParams(List queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT)); - } + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes(), Base64.DEFAULT)); + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java index 13240eaa65e..e957462d963 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/DeleteRequest.java @@ -30,75 +30,75 @@ import java.util.Map; public class DeleteRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public DeleteRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.DELETE, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public DeleteRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.DELETE, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java index 877e2e44e25..844d49c81f9 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PatchRequest.java @@ -30,75 +30,75 @@ import java.util.Map; public class PatchRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PatchRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.PATCH, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PatchRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PATCH, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java index 66383b7d054..85e537bb0aa 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PostRequest.java @@ -30,75 +30,75 @@ import java.util.Map; public class PostRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PostRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.POST, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PostRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.POST, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } diff --git a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java index 80a54c97868..bd7f9dad742 100644 --- a/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java +++ b/samples/client/petstore/android/volley/src/main/java/io/swagger/client/request/PutRequest.java @@ -30,75 +30,75 @@ import java.util.Map; public class PutRequest extends Request { - HttpEntity entity; + HttpEntity entity; - private final Response.Listener mListener; + private final Response.Listener mListener; - String contentType; - Map apiHeaders; - public PutRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { - super(Method.PUT, url, errorListener); - mListener = listener; - this.entity = entity; - this.contentType = contentType; - this.apiHeaders = apiHeaders; + String contentType; + Map apiHeaders; + public PutRequest(String url, Map apiHeaders, String contentType, HttpEntity entity, Response.Listener listener, Response.ErrorListener errorListener) { + super(Method.PUT, url, errorListener); + mListener = listener; + this.entity = entity; + this.contentType = contentType; + this.apiHeaders = apiHeaders; + } + + @Override + public String getBodyContentType() { + if(entity == null) { + return null; + } + return entity.getContentType().getValue(); + } + + @Override + public byte[] getBody() throws AuthFailureError { + if(entity == null) { + return null; + } + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + entity.writeTo(bos); + } + catch (IOException e) { + VolleyLog.e("IOException writing to ByteArrayOutputStream"); + } + return bos.toByteArray(); + } + + @Override + protected Response parseNetworkResponse(NetworkResponse response) { + String parsed; + try { + parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); + } catch (UnsupportedEncodingException e) { + parsed = new String(response.data); + } + return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); + } + + @Override + protected void deliverResponse(String response) { + mListener.onResponse(response); + } + + /* (non-Javadoc) + * @see com.android.volley.Request#getHeaders() + */ + @Override + public Map getHeaders() throws AuthFailureError { + Map headers = super.getHeaders(); + if (headers == null || headers.equals(Collections.emptyMap())) { + headers = new HashMap(); + } + if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { + headers.putAll(apiHeaders); + } + if(contentType != null) { + headers.put("Content-Type", contentType); } - @Override - public String getBodyContentType() { - if(entity == null) { - return null; - } - return entity.getContentType().getValue(); - } - - @Override - public byte[] getBody() throws AuthFailureError { - if(entity == null) { - return null; - } - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - entity.writeTo(bos); - } - catch (IOException e) { - VolleyLog.e("IOException writing to ByteArrayOutputStream"); - } - return bos.toByteArray(); - } - - @Override - protected Response parseNetworkResponse(NetworkResponse response) { - String parsed; - try { - parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); - } catch (UnsupportedEncodingException e) { - parsed = new String(response.data); - } - return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response)); - } - - @Override - protected void deliverResponse(String response) { - mListener.onResponse(response); - } - - /* (non-Javadoc) - * @see com.android.volley.Request#getHeaders() - */ - @Override - public Map getHeaders() throws AuthFailureError { - Map headers = super.getHeaders(); - if (headers == null || headers.equals(Collections.emptyMap())) { - headers = new HashMap(); - } - if (apiHeaders != null && !apiHeaders.equals(Collections.emptyMap())) { - headers.putAll(apiHeaders); - } - if(contentType != null) { - headers.put("Content-Type", contentType); - } - - return headers; - } + return headers; + } } From 83adcf5c06c33dd7ce7d11d1d7e134dc886b059b Mon Sep 17 00:00:00 2001 From: Leonardo Pacheco Date: Wed, 14 Dec 2016 01:23:51 -0200 Subject: [PATCH 166/269] Update README.md (#4390) Included "Prill Tecnologia" to the list of companies using swagger-codegen. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b49bf4994ff..3fccbaff1f0 100644 --- a/README.md +++ b/README.md @@ -799,6 +799,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) - [PostAffiliatePro](https://www.postaffiliatepro.com/) +- [Prill Tecnologia](http://www.prill.com.br) - [QAdept](http://qadept.com/) - [QuantiModo](https://quantimo.do/) - [Rapid7](https://rapid7.com/) From dbb66af73d976f25e943e6934ebfedb41fe247b6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 14 Dec 2016 11:49:15 +0800 Subject: [PATCH 167/269] [C#] Add auto-generated doc for c# 2.0 generator (#4354) * add auto-generated doc for c# 2.0 generator * update readme for c# 2.0 * update readme * update namespace in the doc --- .../languages/CsharpDotNet2ClientCodegen.java | 20 +- .../main/resources/CsharpDotNet2/README.md | 10 - .../resources/CsharpDotNet2/README.mustache | 153 +++++ .../resources/CsharpDotNet2/api_doc.mustache | 97 ++++ .../CsharpDotNet2/model_doc.mustache | 14 + .../Lib/SwaggerClient/.swagger-codegen-ignore | 23 + .../Lib/SwaggerClient/README.md | 128 ++++- .../Lib/SwaggerClient/docs/ApiResponse.md | 11 + .../Lib/SwaggerClient/docs/Category.md | 10 + .../Lib/SwaggerClient/docs/Order.md | 14 + .../Lib/SwaggerClient/docs/Pet.md | 14 + .../Lib/SwaggerClient/docs/PetApi.md | 544 ++++++++++++++++++ .../Lib/SwaggerClient/docs/StoreApi.md | 260 +++++++++ .../Lib/SwaggerClient/docs/Tag.md | 10 + .../Lib/SwaggerClient/docs/User.md | 16 + .../Lib/SwaggerClient/docs/UserApi.md | 506 ++++++++++++++++ .../IO/Swagger/Client/ApiClient.cs | 8 +- .../IO/Swagger/Model/ApiResponse.cs | 2 +- .../IO/Swagger/Model/Category.cs | 2 +- .../CsharpDotNet2/IO/Swagger/Model/Order.cs | 2 +- .../CsharpDotNet2/IO/Swagger/Model/Pet.cs | 2 +- .../CsharpDotNet2/IO/Swagger/Model/Tag.cs | 2 +- .../CsharpDotNet2/IO/Swagger/Model/User.cs | 2 +- 23 files changed, 1826 insertions(+), 24 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md create mode 100644 modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/CsharpDotNet2/api_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/CsharpDotNet2/model_doc.mustache create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/.swagger-codegen-ignore create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/User.md create mode 100644 samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 9537b7abc2c..dbcf9d70613 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -21,6 +21,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege protected String packageVersion = "1.0.0"; protected String clientPackage = "IO.Swagger.Client"; protected String sourceFolder = "src" + File.separator + "main" + File.separator + "CsharpDotNet2"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + public CsharpDotNet2ClientCodegen() { super(); @@ -35,6 +38,8 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege embeddedTemplateDir = templateDir = "CsharpDotNet2"; apiPackage = "IO.Swagger.Api"; modelPackage = "IO.Swagger.Model"; + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); setReservedWordsLowerCase( Arrays.asList( @@ -122,6 +127,9 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege additionalProperties.put(CLIENT_PACKAGE, clientPackage); } + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", @@ -130,7 +138,7 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); - supportingFiles.add(new SupportingFile("README.md", "", "README.md")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @@ -292,4 +300,14 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege return input.replace("*/", "*_/").replace("/*", "/_*"); } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + } diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md deleted file mode 100644 index 5fe03fcb316..00000000000 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Csharp-DotNet2 - -This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d. - -## Dependencies -- Mono compiler -- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator. - - - diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.mustache new file mode 100644 index 00000000000..6056d800a24 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/README.mustache @@ -0,0 +1,153 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Frameworks supported +{{^supportUWP}} +- .NET 2.0 +{{/supportUWP}} +{{#supportUWP}} +- UWP +{{/supportUWP}} + + +## Dependencies +- Mono compiler +- Newtonsoft.Json.7.0.1 +- RestSharp.Net2.1.1.11 + +Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh compile-mono.sh` +- [Windows] TODO + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; +``` + +## Getting Started + +```csharp +using System; +using System.Diagnostics; +using {{apiPackage}}; +using {{packageName}}.Client; +using {{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +}{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api_doc.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api_doc.mustache new file mode 100644 index 00000000000..c61043bf1ea --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api_doc.mustache @@ -0,0 +1,97 @@ +# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```csharp +using System; +using System.Diagnostics; +using {{packageName}}.Api; +using {{packageName}}.Client; +using {{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public void main() + { + {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} + // Configure HTTP basic authorization: {{{name}}} + Configuration.Default.Username = "YOUR_USERNAME"; + Configuration.Default.Password = "YOUR_PASSWORD";{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + Configuration.Default.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN";{{/isOAuth}}{{/authMethods}} + {{/hasAuthMethods}} + + var apiInstance = new {{classname}}(); + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{returnType}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (Exception e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + } + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model_doc.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model_doc.mustache new file mode 100644 index 00000000000..aff3e7e0d1e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/model_doc.mustache @@ -0,0 +1,14 @@ +{{#models}} +{{#model}} +# {{{packageName}}}.Model.{{{classname}}} +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}} +{{/models}} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/.swagger-codegen-ignore b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md index 5fe03fcb316..6cd17fe5c76 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md @@ -1,10 +1,132 @@ -# Csharp-DotNet2 +# IO.Swagger - the C# library for the Swagger Petstore -This generator creates C# code targeting the .Net 2.0 framework. The resulting DLLs can be used in places where .Net 2.0 is the maximum supported version, such as in the Unity3d. +This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. +This C# SDK is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build date: 2016-12-09T16:46:08.135+08:00 +- Build package: class io.swagger.codegen.languages.CsharpDotNet2ClientCodegen + + +## Frameworks supported +- .NET 2.0 + + ## Dependencies - Mono compiler -- Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator. +- Newtonsoft.Json.7.0.1 +- RestSharp.Net2.1.1.11 + +Note: NuGet is downloaded by the mono compilation script and packages are installed with it. No dependency DLLs are bundled with this generator + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh compile-mono.sh` +- [Windows] TODO + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using IO.Swagger.IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.IO.Swagger.Model; +``` + +## Getting Started + +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class Example + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + } + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + +## Documentation for Models + + - [IO.Swagger.Model.ApiResponse](docs/ApiResponse.md) + - [IO.Swagger.Model.Category](docs/Category.md) + - [IO.Swagger.Model.Order](docs/Order.md) + - [IO.Swagger.Model.Pet](docs/Pet.md) + - [IO.Swagger.Model.Tag](docs/Tag.md) + - [IO.Swagger.Model.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md new file mode 100644 index 00000000000..6da90f0a55d --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/ApiResponse.md @@ -0,0 +1,11 @@ +# IO.Swagger.Model.ApiResponse +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int?** | | [optional] [default to null] +**Type** | **string** | | [optional] [default to null] +**Message** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md new file mode 100644 index 00000000000..14f99345925 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Category.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Category +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md new file mode 100644 index 00000000000..029b93a4fcf --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Order.md @@ -0,0 +1,14 @@ +# IO.Swagger.Model.Order +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] [default to null] +**PetId** | **long?** | | [optional] [default to null] +**Quantity** | **int?** | | [optional] [default to null] +**ShipDate** | **DateTime?** | | [optional] [default to null] +**Status** | **string** | Order Status | [optional] [default to null] +**Complete** | **bool?** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md new file mode 100644 index 00000000000..0cfae6a3776 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Pet.md @@ -0,0 +1,14 @@ +# IO.Swagger.Model.Pet +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] [default to null] +**Category** | [**Category**](Category.md) | | [optional] [default to null] +**Name** | **string** | | [default to null] +**PhotoUrls** | **List<string>** | | [default to null] +**Tags** | [**List<Tag>**](Tag.md) | | [optional] [default to null] +**Status** | **string** | pet status in the store | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md new file mode 100644 index 00000000000..2487b1e5fdd --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/PetApi.md @@ -0,0 +1,544 @@ +# IO.Swagger..PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **AddPet** +> void AddPet (Pet body) + +Add a new pet to the store + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class AddPetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + apiInstance.AddPet(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **DeletePet** +> void DeletePet (long? petId, string apiKey) + +Deletes a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeletePetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | Pet id to delete + var apiKey = apiKey_example; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| Pet id to delete | + **apiKey** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByStatus** +> List FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FindPetsByStatusExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var status = new List(); // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List<Pet> result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List**](string.md)| Status values that need to be considered for filter | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **FindPetsByTags** +> List FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class FindPetsByTagsExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List<Pet> result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List**](string.md)| Tags to filter by | + +### Return type + +[**List**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetPetById** +> Pet GetPetById (long? petId) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetPetByIdExample + { + public void main() + { + + // Configure API key authorization: api_key + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdatePet** +> void UpdatePet (Pet body) + +Update an existing pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdatePetExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var body = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + apiInstance.UpdatePet(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long? petId, string name, string status) + +Updates a pet in the store with form data + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet that needs to be updated + var name = name_example; // string | Updated name of the pet (optional) + var status = status_example; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet that needs to be updated | + **name** | **string**| Updated name of the pet | [optional] + **status** | **string**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UploadFile** +> ApiResponse UploadFile (long? petId, string additionalMetadata, System.IO.Stream file) + +uploads an image + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UploadFileExample + { + public void main() + { + + // Configure OAuth2 access token for authorization: petstore_auth + Configuration.Default.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(); + var petId = 789; // long? | ID of pet to update + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + var file = new System.IO.Stream(); // System.IO.Stream | file to upload (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long?**| ID of pet to update | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + **file** | **System.IO.Stream**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md new file mode 100644 index 00000000000..bed83b157f1 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/StoreApi.md @@ -0,0 +1,260 @@ +# IO.Swagger..StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (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 + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeleteOrderExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var orderId = orderId_example; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetInventory** +> Dictionary GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetInventoryExample + { + public void main() + { + + // Configure API key authorization: api_key + Configuration.Default.ApiKey.Add("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // Configuration.Default.ApiKeyPrefix.Add("api_key", "Bearer"); + + var apiInstance = new StoreApi(); + + try + { + // Returns pet inventories by status + Dictionary<String, int?> result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Dictionary** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetOrderById** +> Order GetOrderById (long? orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetOrderByIdExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var orderId = 789; // long? | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **long?**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **PlaceOrder** +> Order PlaceOrder (Order body) + +Place an order for a pet + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class PlaceOrderExample + { + public void main() + { + + var apiInstance = new StoreApi(); + var body = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(body); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md new file mode 100644 index 00000000000..f5ebda46b8c --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/Tag.md @@ -0,0 +1,10 @@ +# IO.Swagger.Model.Tag +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] [default to null] +**Name** | **string** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/User.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/User.md new file mode 100644 index 00000000000..fdf2b4020dc --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/User.md @@ -0,0 +1,16 @@ +# IO.Swagger.Model.User +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long?** | | [optional] [default to null] +**Username** | **string** | | [optional] [default to null] +**FirstName** | **string** | | [optional] [default to null] +**LastName** | **string** | | [optional] [default to null] +**Email** | **string** | | [optional] [default to null] +**Password** | **string** | | [optional] [default to null] +**Phone** | **string** | | [optional] [default to null] +**UserStatus** | **int?** | User Status | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md new file mode 100644 index 00000000000..6b14a5a4373 --- /dev/null +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/docs/UserApi.md @@ -0,0 +1,506 @@ +# IO.Swagger..UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +# **CreateUser** +> void CreateUser (User body) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List body) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List body) + +Creates list of users with given input array + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public void main() + { + + var apiInstance = new UserApi(); + var body = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class DeleteUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class GetUserByNameExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **LoginUser** +> string LoginUser (string username, string password) + +Logs user into the system + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class LoginUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | The user name for login + var password = password_example; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + + + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class LogoutUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **UpdateUser** +> void UpdateUser (string username, User body) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System; +using System.Diagnostics; +using IO.Swagger.Api; +using IO.Swagger.Client; +using IO.Swagger.Model; + +namespace Example +{ + public class UpdateUserExample + { + public void main() + { + + var apiInstance = new UserApi(); + var username = username_example; // string | name that need to be deleted + var body = new User(); // User | Updated user object + + try + { + // Updated user + apiInstance.UpdateUser(username, body); + } + catch (Exception e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs index 4f55f130134..b832ff1d0f9 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs @@ -257,13 +257,13 @@ namespace IO.Swagger.Client // determine which one to use switch(auth) { - case "petstore_auth": - - //TODO support oauth - break; case "api_key": headerParams["api_key"] = GetApiKeyWithPrefix("api_key"); + break; + case "petstore_auth": + + //TODO support oauth break; default: //TODO show warning about security definition not found diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/ApiResponse.cs index 42e259da68a..ee748fc96b1 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/ApiResponse.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// Describes the result of uploading an image resource /// [DataContract] public class ApiResponse { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs index 3e2508259db..1cfd58f9873 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Category.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// A category for a pet /// [DataContract] public class Category { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs index 0f667d9c46d..cce83477933 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Order.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// An order for a pets from the pet store /// [DataContract] public class Order { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs index 27ab53d3767..01f8229ec05 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Pet.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// A pet for sale in the pet store /// [DataContract] public class Pet { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs index 639e1d79eaf..558fb7c5d26 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/Tag.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// A tag for a pet /// [DataContract] public class Tag { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs index f3367f341b9..0da312eb0f4 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Model/User.cs @@ -8,7 +8,7 @@ using Newtonsoft.Json; namespace IO.Swagger.Model { /// - /// + /// A User who is purchasing from the pet store /// [DataContract] public class User { From 4fa3595a41077eb1bee931045d67f2a78c951117 Mon Sep 17 00:00:00 2001 From: Chris Putnam Date: Tue, 13 Dec 2016 22:50:02 -0500 Subject: [PATCH 168/269] [typescript-angular2] Fix syntax error (#4383) * allow function so access token can be derived for each api call * update tests * update type for accessToken to be string or function that returns string * fix syntax error --- .../main/resources/typescript-angular2/configuration.mustache | 2 +- .../petstore-security-test/typescript-angular2/configuration.ts | 2 +- .../petstore/typescript-angular2/default/configuration.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache index dd8d4be9728..a566a180e4e 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/configuration.mustache @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string | () => string; + accessToken: string | (() => string); } \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/configuration.ts b/samples/client/petstore-security-test/typescript-angular2/configuration.ts index dd8d4be9728..a566a180e4e 100644 --- a/samples/client/petstore-security-test/typescript-angular2/configuration.ts +++ b/samples/client/petstore-security-test/typescript-angular2/configuration.ts @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string | () => string; + accessToken: string | (() => string); } \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/configuration.ts b/samples/client/petstore/typescript-angular2/default/configuration.ts index dd8d4be9728..a566a180e4e 100644 --- a/samples/client/petstore/typescript-angular2/default/configuration.ts +++ b/samples/client/petstore/typescript-angular2/default/configuration.ts @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string | () => string; + accessToken: string | (() => string); } \ No newline at end of file From 90cf1cab539d9f4e76832a6026b46a3dfff5d1e4 Mon Sep 17 00:00:00 2001 From: Bruno Santos Date: Tue, 13 Dec 2016 22:51:14 -0500 Subject: [PATCH 169/269] Date type should not include time (#4385) Removed time section from Date type in example generators. Issue #4359 --- .../main/java/io/swagger/codegen/examples/ExampleGenerator.java | 2 +- .../java/io/swagger/codegen/examples/XmlExampleGenerator.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index 228e5afb90d..26a4422f071 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -93,7 +93,7 @@ public class ExampleGenerator { }; } } else if (property instanceof DateProperty) { - return "2000-01-23T04:56:07.000+00:00"; + return "2000-01-23"; } else if (property instanceof DateTimeProperty) { return "2000-01-23T04:56:07.000+00:00"; } else if (property instanceof DecimalProperty) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index 3b7700115e1..ed9ab123354 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -180,7 +180,7 @@ public class XmlExampleGenerator { if (property.getExample() != null) { return property.getExample().toString(); } else { - return "2000-01-23T04:56:07.000Z"; + return "2000-01-23"; } } else if (property instanceof IntegerProperty) { if (property.getExample() != null) { From 5867728724b34dd1d9aa41162ccdc2bce4a8094c Mon Sep 17 00:00:00 2001 From: Matan Rubin Date: Wed, 14 Dec 2016 07:58:56 +0200 Subject: [PATCH 170/269] [JaxRS-CXF][bug #4330] support containers in return types (#4339) * [JaxRS-CXF][bug #4330] support containers in return types before this commit if a method returned a container (List or Map) of THING (i.e. List or Map) the generated return type would drop the container and only leave THING. this commit fixes this issue such that the container type is properly generated. * regenerate jaxrs-cxf petstore sample --- .../main/resources/JavaJaxRS/cxf/api.mustache | 2 +- .../JavaJaxRS/cxf/apiServiceImpl.mustache | 2 +- .../resources/JavaJaxRS/cxf/api_test.mustache | 2 +- .../JavaJaxRS/cxf/returnTypes.mustache | 1 + .../src/gen/java/io/swagger/api/PetApi.java | 22 +++++++++---------- .../src/gen/java/io/swagger/api/StoreApi.java | 10 ++++----- .../src/gen/java/io/swagger/api/UserApi.java | 20 ++++++++--------- .../swagger/api/impl/PetApiServiceImpl.java | 20 ++++++++--------- .../swagger/api/impl/StoreApiServiceImpl.java | 8 +++---- .../swagger/api/impl/UserApiServiceImpl.java | 18 +++++++-------- 10 files changed, 50 insertions(+), 55 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/returnTypes.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 7fbcc9cea4d..47062c394d2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -37,7 +37,7 @@ public interface {{classname}} { @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) {{/hasProduces}} @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache index ee5d8269955..70f5f4f37de 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/apiServiceImpl.mustache @@ -28,7 +28,7 @@ import org.springframework.stereotype.Service; public class {{classname}}ServiceImpl implements {{classname}} { {{#operations}} {{#operation}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>bodyParams}}{{>formParamsImpl}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { // TODO: Implement... {{^vendorExtensions.x-java-is-response-void}}return null;{{/vendorExtensions.x-java-is-response-void}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache index 34308df4314..919e7d38206 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api_test.mustache @@ -103,7 +103,7 @@ public class {{classname}}Test { {{#allParams}} {{^isFile}}{{{dataType}}} {{paramName}} = null;{{/isFile}}{{#isFile}}org.apache.cxf.jaxrs.ext.multipart.Attachment {{paramName}} = null;{{/isFile}} {{/allParams}} - //{{^vendorExtensions.x-java-is-response-void}}{{{returnType}}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + //{{^vendorExtensions.x-java-is-response-void}}{{>returnTypes}} response = {{/vendorExtensions.x-java-is-response-void}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{^vendorExtensions.x-java-is-response-void}}//assertNotNull(response);{{/vendorExtensions.x-java-is-response-void}} // TODO: test validations diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/returnTypes.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/returnTypes.mustache new file mode 100644 index 00000000000..c8f7a56938a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/returnTypes.mustache @@ -0,0 +1 @@ +{{#returnContainer}}{{#isMapContainer}}Map{{/isMapContainer}}{{#isListContainer}}List<{{{returnType}}}>{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java index 608b51f96d8..4ef2db0e204 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import java.io.InputStream; import java.io.OutputStream; @@ -18,8 +18,6 @@ import io.swagger.annotations.ApiOperation; @Path("/") @Api(value = "/", description = "") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) public interface PetApi { @POST @@ -27,51 +25,51 @@ public interface PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) - public void addPet(Pet body); + public void addPet(Pet body); @DELETE @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Deletes a pet", tags={ "pet", }) - public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); @GET @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) - public Pet findPetsByStatus(@QueryParam("status")List status); + public List findPetsByStatus(@QueryParam("status")List status); @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) - public Pet findPetsByTags(@QueryParam("tags")List tags); + public List findPetsByTags(@QueryParam("tags")List tags); @GET @Path("/pet/{petId}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Find pet by ID", tags={ "pet", }) - public Pet getPetById(@PathParam("petId") Long petId); + public Pet getPetById(@PathParam("petId") Long petId); @PUT @Path("/pet") @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Update an existing pet", tags={ "pet", }) - public void updatePet(Pet body); + public void updatePet(Pet body); @POST @Path("/pet/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) - public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); @POST @Path("/pet/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) @ApiOperation(value = "uploads an image", tags={ "pet" }) - public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); + public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java index 87a583b8712..e26c47769b4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -17,32 +17,30 @@ import io.swagger.annotations.ApiOperation; @Path("/") @Api(value = "/", description = "") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) public interface StoreApi { @DELETE @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) - public void deleteOrder(@PathParam("orderId") String orderId); + public void deleteOrder(@PathParam("orderId") String orderId); @GET @Path("/store/inventory") @Produces({ "application/json" }) @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) - public Integer getInventory(); + public Map getInventory(); @GET @Path("/store/order/{orderId}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) - public Order getOrderById(@PathParam("orderId") Long orderId); + public Order getOrderById(@PathParam("orderId") Long orderId); @POST @Path("/store/order") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Place an order for a pet", tags={ "store" }) - public Order placeOrder(Order body); + public Order placeOrder(Order body); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java index 528af584f46..a51b1fe0c70 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import java.io.InputStream; import java.io.OutputStream; @@ -17,56 +17,54 @@ import io.swagger.annotations.ApiOperation; @Path("/") @Api(value = "/", description = "") -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) public interface UserApi { @POST @Path("/user") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Create user", tags={ "user", }) - public void createUser(User body); + public void createUser(User body); @POST @Path("/user/createWithArray") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithArrayInput(List body); + public void createUsersWithArrayInput(List body); @POST @Path("/user/createWithList") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithListInput(List body); + public void createUsersWithListInput(List body); @DELETE @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Delete user", tags={ "user", }) - public void deleteUser(@PathParam("username") String username); + public void deleteUser(@PathParam("username") String username); @GET @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Get user by user name", tags={ "user", }) - public User getUserByName(@PathParam("username") String username); + public User getUserByName(@PathParam("username") String username); @GET @Path("/user/login") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Logs user into the system", tags={ "user", }) - public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); @GET @Path("/user/logout") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) - public void logoutUser(); + public void logoutUser(); @PUT @Path("/user/{username}") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Updated user", tags={ "user" }) - public void updateUser(@PathParam("username") String username, User body); + public void updateUser(@PathParam("username") String username, User body); } diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 9c952820070..d9b9345d339 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,9 +1,9 @@ package io.swagger.api.impl; import io.swagger.api.*; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import java.io.InputStream; import java.io.OutputStream; @@ -19,49 +19,49 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; public class PetApiServiceImpl implements PetApi { - public void addPet(Pet body) { + public void addPet(Pet body) { // TODO: Implement... } - public void deletePet(Long petId, String apiKey) { + public void deletePet(Long petId, String apiKey) { // TODO: Implement... } - public Pet findPetsByStatus(List status) { + public List findPetsByStatus(List status) { // TODO: Implement... return null; } - public Pet findPetsByTags(List tags) { + public List findPetsByTags(List tags) { // TODO: Implement... return null; } - public Pet getPetById(Long petId) { + public Pet getPetById(Long petId) { // TODO: Implement... return null; } - public void updatePet(Pet body) { + public void updatePet(Pet body) { // TODO: Implement... } - public void updatePetWithForm(Long petId, String name, String status) { + public void updatePetWithForm(Long petId, String name, String status) { // TODO: Implement... } - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { // TODO: Implement... return null; diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index cbcc2de9e2a..3f791097b6b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -18,25 +18,25 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; public class StoreApiServiceImpl implements StoreApi { - public void deleteOrder(String orderId) { + public void deleteOrder(String orderId) { // TODO: Implement... } - public Integer getInventory() { + public Map getInventory() { // TODO: Implement... return null; } - public Order getOrderById(Long orderId) { + public Order getOrderById(Long orderId) { // TODO: Implement... return null; } - public Order placeOrder(Order body) { + public Order placeOrder(Order body) { // TODO: Implement... return null; diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 8fac5414a23..861273cfb7b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,8 +1,8 @@ package io.swagger.api.impl; import io.swagger.api.*; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import java.io.InputStream; import java.io.OutputStream; @@ -18,49 +18,49 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; public class UserApiServiceImpl implements UserApi { - public void createUser(User body) { + public void createUser(User body) { // TODO: Implement... } - public void createUsersWithArrayInput(List body) { + public void createUsersWithArrayInput(List body) { // TODO: Implement... } - public void createUsersWithListInput(List body) { + public void createUsersWithListInput(List body) { // TODO: Implement... } - public void deleteUser(String username) { + public void deleteUser(String username) { // TODO: Implement... } - public User getUserByName(String username) { + public User getUserByName(String username) { // TODO: Implement... return null; } - public String loginUser(String username, String password) { + public String loginUser(String username, String password) { // TODO: Implement... return null; } - public void logoutUser() { + public void logoutUser() { // TODO: Implement... } - public void updateUser(String username, User body) { + public void updateUser(String username, User body) { // TODO: Implement... From a13dee7167743d238e014d337e61d578038356b9 Mon Sep 17 00:00:00 2001 From: lukoyanov Date: Wed, 14 Dec 2016 12:32:49 +0300 Subject: [PATCH 171/269] [Java] Play! Framework 2.4 WS client support + retrofit2 (#4270) * implemented core integration with play 2.4 ws * added shell script to test on CI * added shell script to composite file for all java generators * added some comments changed promise param to Response to allow access to http status code and raw response if needed * removed unnecessary whitespace changes * added java7 compatibility, play ws deps to pom.xml * added generated play24 client * fixed imports --- bin/java-petstore-all.sh | 1 + bin/java-petstore-retrofit2-play24.json | 1 + bin/java-petstore-retrofit2-play24.sh | 34 ++ .../codegen/languages/JavaClientCodegen.java | 62 ++- .../Java/libraries/retrofit2/api.mustache | 7 +- .../retrofit2/play24/ApiClient.mustache | 136 ++++++ .../play24/Play24CallAdapterFactory.mustache | 90 ++++ .../play24/Play24CallFactory.mustache | 210 ++++++++ .../retrofit2/play24/auth/ApiKeyAuth.mustache | 67 +++ .../Java/libraries/retrofit2/pom.mustache | 37 ++ .../options/JavaClientOptionsProvider.java | 2 +- .../petstore/java/retrofit2-play24/.gitignore | 21 + .../retrofit2-play24/.swagger-codegen-ignore | 23 + .../java/retrofit2-play24/.travis.yml | 17 + .../petstore/java/retrofit2-play24/README.md | 39 ++ .../java/retrofit2-play24/build.gradle | 113 +++++ .../petstore/java/retrofit2-play24/build.sbt | 21 + .../docs/AdditionalPropertiesClass.md | 11 + .../java/retrofit2-play24/docs/Animal.md | 11 + .../java/retrofit2-play24/docs/AnimalFarm.md | 9 + .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../docs/ArrayOfNumberOnly.md | 10 + .../java/retrofit2-play24/docs/ArrayTest.md | 12 + .../java/retrofit2-play24/docs/Cat.md | 10 + .../java/retrofit2-play24/docs/Category.md | 11 + .../java/retrofit2-play24/docs/ClassModel.md | 10 + .../java/retrofit2-play24/docs/Client.md | 10 + .../java/retrofit2-play24/docs/Dog.md | 10 + .../java/retrofit2-play24/docs/EnumArrays.md | 27 ++ .../java/retrofit2-play24/docs/EnumClass.md | 14 + .../java/retrofit2-play24/docs/EnumTest.md | 37 ++ .../java/retrofit2-play24/docs/FakeApi.md | 191 ++++++++ .../java/retrofit2-play24/docs/FormatTest.md | 22 + .../retrofit2-play24/docs/HasOnlyReadOnly.md | 11 + .../java/retrofit2-play24/docs/MapTest.md | 19 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../retrofit2-play24/docs/Model200Response.md | 11 + .../retrofit2-play24/docs/ModelApiResponse.md | 12 + .../java/retrofit2-play24/docs/ModelReturn.md | 10 + .../java/retrofit2-play24/docs/Name.md | 13 + .../java/retrofit2-play24/docs/NumberOnly.md | 10 + .../java/retrofit2-play24/docs/Order.md | 24 + .../java/retrofit2-play24/docs/OuterEnum.md | 14 + .../java/retrofit2-play24/docs/Pet.md | 24 + .../java/retrofit2-play24/docs/PetApi.md | 452 ++++++++++++++++++ .../retrofit2-play24/docs/ReadOnlyFirst.md | 11 + .../retrofit2-play24/docs/SpecialModelName.md | 10 + .../java/retrofit2-play24/docs/StoreApi.md | 198 ++++++++ .../java/retrofit2-play24/docs/Tag.md | 11 + .../java/retrofit2-play24/docs/User.md | 17 + .../java/retrofit2-play24/docs/UserApi.md | 376 +++++++++++++++ .../java/retrofit2-play24/git_push.sh | 52 ++ .../java/retrofit2-play24/gradle.properties | 2 + .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 53639 bytes .../gradle/wrapper/gradle-wrapper.properties | 6 + .../petstore/java/retrofit2-play24/gradlew | 160 +++++++ .../java/retrofit2-play24/gradlew.bat | 90 ++++ .../petstore/java/retrofit2-play24/pom.xml | 190 ++++++++ .../java/retrofit2-play24/settings.gradle | 1 + .../src/main/AndroidManifest.xml | 3 + .../java/io/swagger/client/ApiClient.java | 136 ++++++ .../io/swagger/client/CollectionFormats.java | 95 ++++ .../src/main/java/io/swagger/client/Pair.java | 52 ++ .../client/Play24CallAdapterFactory.java | 90 ++++ .../io/swagger/client/Play24CallFactory.java | 210 ++++++++ .../io/swagger/client/RFC3339DateFormat.java | 32 ++ .../java/io/swagger/client/StringUtil.java | 55 +++ .../java/io/swagger/client/api/FakeApi.java | 86 ++++ .../java/io/swagger/client/api/PetApi.java | 133 ++++++ .../java/io/swagger/client/api/StoreApi.java | 68 +++ .../java/io/swagger/client/api/UserApi.java | 118 +++++ .../io/swagger/client/auth/ApiKeyAuth.java | 78 +++ .../swagger/client/auth/Authentication.java | 29 ++ .../model/AdditionalPropertiesClass.java | 126 +++++ .../java/io/swagger/client/model/Animal.java | 119 +++++ .../io/swagger/client/model/AnimalFarm.java | 66 +++ .../model/ArrayOfArrayOfNumberOnly.java | 98 ++++ .../client/model/ArrayOfNumberOnly.java | 98 ++++ .../io/swagger/client/model/ArrayTest.java | 154 ++++++ .../java/io/swagger/client/model/Cat.java | 92 ++++ .../io/swagger/client/model/Category.java | 113 +++++ .../io/swagger/client/model/ClassModel.java | 91 ++++ .../java/io/swagger/client/model/Client.java | 90 ++++ .../java/io/swagger/client/model/Dog.java | 92 ++++ .../io/swagger/client/model/EnumArrays.java | 180 +++++++ .../io/swagger/client/model/EnumClass.java | 53 ++ .../io/swagger/client/model/EnumTest.java | 250 ++++++++++ .../io/swagger/client/model/FormatTest.java | 395 +++++++++++++++ .../swagger/client/model/HasOnlyReadOnly.java | 95 ++++ .../java/io/swagger/client/model/MapTest.java | 156 ++++++ ...ropertiesAndAdditionalPropertiesClass.java | 146 ++++++ .../client/model/Model200Response.java | 114 +++++ .../client/model/ModelApiResponse.java | 136 ++++++ .../io/swagger/client/model/ModelReturn.java | 91 ++++ .../java/io/swagger/client/model/Name.java | 143 ++++++ .../io/swagger/client/model/NumberOnly.java | 91 ++++ .../java/io/swagger/client/model/Order.java | 238 +++++++++ .../io/swagger/client/model/OuterEnum.java | 53 ++ .../java/io/swagger/client/model/Pet.java | 253 ++++++++++ .../swagger/client/model/ReadOnlyFirst.java | 104 ++++ .../client/model/SpecialModelName.java | 90 ++++ .../java/io/swagger/client/model/Tag.java | 113 +++++ .../java/io/swagger/client/model/User.java | 251 ++++++++++ .../io/swagger/client/api/FakeApiTest.java | 88 ++++ .../io/swagger/client/api/PetApiTest.java | 137 ++++++ .../io/swagger/client/api/StoreApiTest.java | 77 +++ .../io/swagger/client/api/UserApiTest.java | 131 +++++ 107 files changed, 8713 insertions(+), 18 deletions(-) create mode 100644 bin/java-petstore-retrofit2-play24.json create mode 100755 bin/java-petstore-retrofit2-play24.sh create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/ApiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallAdapterFactory.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallFactory.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/auth/ApiKeyAuth.mustache create mode 100644 samples/client/petstore/java/retrofit2-play24/.gitignore create mode 100644 samples/client/petstore/java/retrofit2-play24/.swagger-codegen-ignore create mode 100644 samples/client/petstore/java/retrofit2-play24/.travis.yml create mode 100644 samples/client/petstore/java/retrofit2-play24/README.md create mode 100644 samples/client/petstore/java/retrofit2-play24/build.gradle create mode 100644 samples/client/petstore/java/retrofit2-play24/build.sbt create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Animal.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Cat.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Category.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ClassModel.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Client.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Dog.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/EnumArrays.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/EnumClass.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/FormatTest.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/MapTest.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Model200Response.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Name.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Order.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Pet.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/PetApi.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/Tag.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/User.md create mode 100644 samples/client/petstore/java/retrofit2-play24/docs/UserApi.md create mode 100644 samples/client/petstore/java/retrofit2-play24/git_push.sh create mode 100644 samples/client/petstore/java/retrofit2-play24/gradle.properties create mode 100644 samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.jar create mode 100644 samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.properties create mode 100644 samples/client/petstore/java/retrofit2-play24/gradlew create mode 100644 samples/client/petstore/java/retrofit2-play24/gradlew.bat create mode 100644 samples/client/petstore/java/retrofit2-play24/pom.xml create mode 100644 samples/client/petstore/java/retrofit2-play24/settings.gradle create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/AndroidManifest.xml create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/CollectionFormats.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallAdapterFactory.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallFactory.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/RFC3339DateFormat.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumClass.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/FakeApiTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/PetApiTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/StoreApiTest.java create mode 100644 samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/UserApiTest.java diff --git a/bin/java-petstore-all.sh b/bin/java-petstore-all.sh index d3e98a74894..fbd2ca65cad 100755 --- a/bin/java-petstore-all.sh +++ b/bin/java-petstore-all.sh @@ -9,3 +9,4 @@ ./bin/java-petstore-retrofit2.sh ./bin/java-petstore-retrofit2rx.sh ./bin/java8-petstore-jersey2.sh +./bin/java-petstore-retrofit2-play24.sh diff --git a/bin/java-petstore-retrofit2-play24.json b/bin/java-petstore-retrofit2-play24.json new file mode 100644 index 00000000000..020d1df198a --- /dev/null +++ b/bin/java-petstore-retrofit2-play24.json @@ -0,0 +1 @@ +{"useBeanValidation":"true","enableBuilderSupport":"true","library":"retrofit2", "usePlay24WS":"true"} \ No newline at end of file diff --git a/bin/java-petstore-retrofit2-play24.sh b/bin/java-petstore-retrofit2-play24.sh new file mode 100755 index 00000000000..43f63fb6251 --- /dev/null +++ b/bin/java-petstore-retrofit2-play24.sh @@ -0,0 +1,34 @@ +#!/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-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2-play24.json -o samples/client/petstore/java/retrofit2-play24" + +echo "Removing files and folders under samples/client/petstore/java/retrofit2-play24/src/main" +rm -rf samples/client/petstore/java/retrofit2-play24/src/main +find samples/client/petstore/java/retrofit2-play24 -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +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 47d1f4232ae..ab4345f997a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -1,26 +1,16 @@ package io.swagger.codegen.languages; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Pattern; - +import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; +import io.swagger.codegen.languages.features.PerformBeanValidationFeatures; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import io.swagger.codegen.CliOption; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenModel; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.SupportingFile; -import io.swagger.codegen.languages.features.BeanValidationFeatures; -import io.swagger.codegen.languages.features.PerformBeanValidationFeatures; +import java.io.File; +import java.util.*; +import java.util.regex.Pattern; public class JavaClientCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, PerformBeanValidationFeatures { @@ -30,6 +20,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen private static final Logger LOGGER = LoggerFactory.getLogger(JavaClientCodegen.class); public static final String USE_RX_JAVA = "useRxJava"; + public static final String USE_PLAY24_WS = "usePlay24WS"; public static final String PARCELABLE_MODEL = "parcelableModel"; public static final String RETROFIT_1 = "retrofit"; @@ -37,6 +28,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen protected String gradleWrapperPackage = "gradle.wrapper"; protected boolean useRxJava = false; + protected boolean usePlay24WS = false; protected boolean parcelableModel = false; protected boolean useBeanValidation = false; protected boolean performBeanValidation = false; @@ -52,6 +44,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen cliOptions.add(CliOption.newBoolean(USE_RX_JAVA, "Whether to use the RxJava adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(PARCELABLE_MODEL, "Whether to generate models for Android that implement Parcelable with the okhttp-gson library.")); + cliOptions.add(CliOption.newBoolean(USE_PLAY24_WS, "Use Play! 2.4 Async HTTP client (Play WS API)")); cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1 library.")); cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); cliOptions.add(CliOption.newBoolean(PERFORM_BEANVALIDATION, "Perform BeanValidation")); @@ -94,6 +87,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen if (additionalProperties.containsKey(USE_RX_JAVA)) { this.setUseRxJava(Boolean.valueOf(additionalProperties.get(USE_RX_JAVA).toString())); } + if (additionalProperties.containsKey(USE_PLAY24_WS)) { + this.setUsePlay24WS(Boolean.valueOf(additionalProperties.get(USE_PLAY24_WS).toString())); + } + additionalProperties.put(USE_PLAY24_WS, usePlay24WS); + if (additionalProperties.containsKey(PARCELABLE_MODEL)) { this.setParcelableModel(Boolean.valueOf(additionalProperties.get(PARCELABLE_MODEL).toString())); } @@ -177,6 +175,33 @@ public class JavaClientCodegen extends AbstractJavaCodegen LOGGER.error("Unknown library option (-l/--library): " + getLibrary()); } + if (Boolean.TRUE.equals(additionalProperties.get(USE_PLAY24_WS))) { + // remove unsupported auth + Iterator iter = supportingFiles.iterator(); + while (iter.hasNext()) { + SupportingFile sf = iter.next(); + if (sf.templateFile.startsWith("auth/")) { + iter.remove(); + } + } + + // auth + supportingFiles.add(new SupportingFile("play24/auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); + + // api client + supportingFiles.add(new SupportingFile("play24/ApiClient.mustache", invokerFolder, "ApiClient.java")); + + // adapters + supportingFiles + .add(new SupportingFile("play24/Play24CallFactory.mustache", invokerFolder, "Play24CallFactory.java")); + supportingFiles.add(new SupportingFile("play24/Play24CallAdapterFactory.mustache", invokerFolder, + "Play24CallAdapterFactory.java")); + additionalProperties.put("jackson", "true"); + additionalProperties.remove("gson"); + } + if (additionalProperties.containsKey("jackson") ) { supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); } @@ -312,6 +337,11 @@ public class JavaClientCodegen extends AbstractJavaCodegen this.useRxJava = useRxJava; } + public void setUsePlay24WS(boolean usePlay24WS) { + this.usePlay24WS = usePlay24WS; + } + + public void setParcelableModel(boolean parcelableModel) { this.parcelableModel = parcelableModel; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 3b32a240726..0296d4afb7a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -18,6 +18,11 @@ import java.util.List; import java.util.Map; {{/fullJavaUtil}} +{{#usePlay24WS}} +import play.libs.F; +import retrofit2.Response; +{{/usePlay24WS}} + {{#operations}} public interface {{classname}} { {{#operation}} @@ -39,7 +44,7 @@ public interface {{classname}} { {{/prioritizedContentTypes}} {{/formParams}} @{{httpMethod}}("{{path}}") - {{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}({{^allParams}});{{/allParams}} + {{^usePlay24WS}}{{#useRxJava}}Observable{{/useRxJava}}{{^useRxJava}}Call{{/useRxJava}}{{/usePlay24WS}}{{#usePlay24WS}}F.Promise{{#usePlay24WS}}>{{/usePlay24WS}} {{operationId}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/ApiClient.mustache new file mode 100644 index 00000000000..5c871c62073 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/ApiClient.mustache @@ -0,0 +1,136 @@ +package {{invokerPackage}}; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.*; + +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import play.libs.Json; +import play.libs.ws.WSClient; + +import {{invokerPackage}}.Play24CallAdapterFactory; +import {{invokerPackage}}.Play24CallFactory; + +import okhttp3.Interceptor; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.Authentication; + +/** + * API client + */ +public class ApiClient { + + /** Underlying HTTP-client */ + private WSClient wsClient; + + /** Supported auths */ + private Map authentications; + + /** API base path */ + private String basePath = "{{{basePath}}}"; + + public ApiClient(WSClient wsClient) { + this(); + this.wsClient = wsClient; + } + + public ApiClient() { + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap<>();{{#authMethods}}{{#isBasic}} + // authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + // authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + } + + /** + * Creates a retrofit2 client for given API interface + */ + public S createService(Class serviceClass) { + if(!basePath.endsWith("/")) { + basePath = basePath + "/"; + } + + Map extraHeaders = new HashMap<>(); + List extraQueryParams = new ArrayList<>(); + + for (String authName : authentications.keySet()) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + + auth.applyToParams(extraQueryParams, extraHeaders); + } + + return new Retrofit.Builder() + .baseUrl(basePath) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(JacksonConverterFactory.create(Json.mapper())) + .callFactory(new Play24CallFactory(wsClient, extraHeaders, extraQueryParams)) + .addCallAdapterFactory(new Play24CallAdapterFactory()) + .build() + .create(serviceClass); + } + + /** + * Helper method to set API base path + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + +} + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallAdapterFactory.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallAdapterFactory.mustache new file mode 100644 index 00000000000..c41dc9ba1aa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallAdapterFactory.mustache @@ -0,0 +1,90 @@ +package {{invokerPackage}}; + +import play.libs.F; +import retrofit2.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; + +/** + * Creates {@link CallAdapter} instances that convert {@link Call} into {@link play.libs.F.Promise} + */ +public class Play24CallAdapterFactory extends CallAdapter.Factory { + + @Override + public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { + if (!(returnType instanceof ParameterizedType)) { + return null; + } + + ParameterizedType type = (ParameterizedType) returnType; + if (type.getRawType() != F.Promise.class) { + return null; + } + + return createAdapter((ParameterizedType) returnType); + } + + private Type getTypeParam(ParameterizedType type) { + Type[] types = type.getActualTypeArguments(); + if (types.length != 1) { + throw new IllegalStateException("Must be exactly one type parameter"); + } + + Type paramType = types[0]; + if (paramType instanceof WildcardType) { + return ((WildcardType) paramType).getUpperBounds()[0]; + } + + return paramType; + } + + private CallAdapter> createAdapter(ParameterizedType returnType) { + Type parameterType = getTypeParam(returnType); + return new ValueAdapter(parameterType); + } + + /** + * Adpater that coverts values returned by API interface into Play promises + */ + static final class ValueAdapter implements CallAdapter> { + + private final Type responseType; + + ValueAdapter(Type responseType) { + this.responseType = responseType; + } + + @Override + public Type responseType() { + return responseType; + } + + @Override + public F.Promise adapt(final Call call) { + final F.RedeemablePromise promise = F.RedeemablePromise.empty(); + + call.enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + promise.success(response.body()); + } else { + promise.failure(new Exception(response.errorBody().toString())); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + promise.failure(t); + } + + }); + + return promise; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallFactory.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallFactory.mustache new file mode 100644 index 00000000000..2a8dce8329e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/Play24CallFactory.mustache @@ -0,0 +1,210 @@ +package {{invokerPackage}}; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSource; +import play.libs.F; +import play.libs.ws.WSClient; +import play.libs.ws.WSRequest; +import play.libs.ws.WSResponse; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Creates {@link Call} instances that invoke underlying {@link WSClient} + */ +public class Play24CallFactory implements okhttp3.Call.Factory { + + /** PlayWS http client */ + private final WSClient wsClient; + + /** Extra headers to add to request */ + private Map extraHeaders = new HashMap<>(); + + /** Extra query parameters to add to request */ + private List extraQueryParams = new ArrayList<>(); + + public Play24CallFactory(WSClient wsClient) { + this.wsClient = wsClient; + } + + public Play24CallFactory(WSClient wsClient, Map extraHeaders, + List extraQueryParams) { + this.wsClient = wsClient; + + this.extraHeaders.putAll(extraHeaders); + this.extraQueryParams.addAll(extraQueryParams); + } + + @Override + public Call newCall(Request request) { + // add extra headers + Request.Builder rb = request.newBuilder(); + for (Map.Entry header : this.extraHeaders.entrySet()) { + rb.addHeader(header.getKey(), header.getValue()); + } + + // add extra query params + if (!this.extraQueryParams.isEmpty()) { + String newQuery = request.url().uri().getQuery(); + for (Pair queryParam : this.extraQueryParams) { + String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue()); + if (newQuery == null) { + newQuery = param; + } else { + newQuery += "&" + param; + } + } + + URI newUri; + try { + newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(), + request.url().uri().getPath(), newQuery, request.url().uri().getFragment()); + rb.url(newUri.toURL()); + } catch (MalformedURLException | URISyntaxException e) { + throw new RuntimeException("Error while updating an url", e); + } + } + + return new PlayWSCall(wsClient, rb.build()); + } + + /** + * Call implementation that delegates to Play WS Client + */ + static class PlayWSCall implements Call { + + private final WSClient wsClient; + private WSRequest wsRequest; + + private final Request request; + + public PlayWSCall(WSClient wsClient, Request request) { + this.wsClient = wsClient; + this.request = request; + } + + @Override + public Request request() { + return request; + } + + @Override + public void enqueue(final okhttp3.Callback responseCallback) { + final Call call = this; + final F.Promise promise = executeAsync(); + + promise.onRedeem(new F.Callback() { + + @Override + public void invoke(WSResponse wsResponse) throws Throwable { + responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(wsResponse)); + } + + }); + + promise.onFailure(new F.Callback() { + + @Override + public void invoke(Throwable throwable) throws Throwable { + if (throwable instanceof IOException) { + responseCallback.onFailure(call, (IOException) throwable); + } else { + responseCallback.onFailure(call, new IOException(throwable)); + } + } + + }); + + } + + F.Promise executeAsync() { + try { + wsRequest = wsClient.url(request.url().uri().toString()); + addHeaders(wsRequest); + if (request.body() != null) { + addBody(wsRequest); + } + + return wsRequest.execute(request.method()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + private void addHeaders(WSRequest wsRequest) { + for(Map.Entry> entry : request.headers().toMultimap().entrySet()) { + List values = entry.getValue(); + for (String value : values) { + wsRequest.setHeader(entry.getKey(), value); + } + } + } + + private void addBody(WSRequest wsRequest) throws IOException { + Buffer buffer = new Buffer(); + request.body().writeTo(buffer); + wsRequest.setBody(buffer.inputStream()); + wsRequest.setContentType(request.body().contentType().toString()); + } + + private Response toWSResponse(final WSResponse r) { + final Response.Builder builder = new Response.Builder(); + builder.request(request) + .code(r.getStatus()) + .body(new ResponseBody() { + + @Override + public MediaType contentType() { + return MediaType.parse(r.getHeader("Content-Type")); + } + + @Override + public long contentLength() { + return r.getBody().getBytes().length; + } + + @Override + public BufferedSource source() { + return new Buffer().write(r.getBody().getBytes()); + } + }); + + for (Map.Entry> entry : r.getAllHeaders().entrySet()) { + for (String value : entry.getValue()) { + builder.addHeader(entry.getKey(), value); + } + } + + builder.protocol(Protocol.HTTP_1_1); + return builder.build(); + } + + @Override + public Response execute() throws IOException { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public boolean isExecuted() { + return false; + } + + @Override + public boolean isCanceled() { + return false; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..5652db326b5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/play24/auth/ApiKeyAuth.mustache @@ -0,0 +1,67 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import java.util.Map; +import java.util.List; + +/** + * Holds ApiKey auth info + */ +{{>generatedAnnotation}} +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + 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; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index cacb10ef9e7..474f980a020 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -148,6 +148,40 @@ ${retrofit-version} {{/useRxJava}} + + {{#usePlay24WS}} + + + com.squareup.retrofit2 + converter-jackson + ${retrofit-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}} + ${jackson-version} + + + com.typesafe.play + play-java-ws_2.10 + 2.4.6 + + {{/usePlay24WS}} @@ -164,6 +198,9 @@ ${java.version} 1.5.9 2.1.0 + {{#usePlay24WS}} + 2.7.5 + {{/usePlay24WS}} {{#useRxJava}} 1.1.6 {{/useRxJava}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java index 83fe85bcdfb..1fb1b86604d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaClientOptionsProvider.java @@ -1,6 +1,5 @@ package io.swagger.codegen.options; -import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaClientCodegen; @@ -18,6 +17,7 @@ public class JavaClientOptionsProvider extends JavaOptionsProvider { Map options = new HashMap(super.createOptions()); options.put(CodegenConstants.LIBRARY, DEFAULT_LIBRARY_VALUE); options.put(JavaClientCodegen.USE_RX_JAVA, "false"); + options.put(JavaClientCodegen.USE_PLAY24_WS, "false"); options.put(JavaClientCodegen.PARCELABLE_MODEL, "false"); options.put(JavaClientCodegen.SUPPORT_JAVA6, "false"); options.put(JavaClientCodegen.USE_BEANVALIDATION, "false"); diff --git a/samples/client/petstore/java/retrofit2-play24/.gitignore b/samples/client/petstore/java/retrofit2-play24/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/retrofit2-play24/.swagger-codegen-ignore b/samples/client/petstore/java/retrofit2-play24/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/retrofit2-play24/.travis.yml b/samples/client/petstore/java/retrofit2-play24/.travis.yml new file mode 100644 index 00000000000..70cb81a67c2 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/.travis.yml @@ -0,0 +1,17 @@ +# +# Generated by: https://github.com/swagger-api/swagger-codegen.git +# +language: java +jdk: + - oraclejdk8 + - oraclejdk7 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + - mvn test + # uncomment below to test using gradle + # - gradle test + # uncomment below to test using sbt + # - sbt test diff --git a/samples/client/petstore/java/retrofit2-play24/README.md b/samples/client/petstore/java/retrofit2-play24/README.md new file mode 100644 index 00000000000..730060e131b --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/README.md @@ -0,0 +1,39 @@ +# swagger-java-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation & Usage + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: + +```xml + + io.swagger + swagger-java-client + 1.0.0 + compile + + +``` + +## Author + +apiteam@swagger.io + + diff --git a/samples/client/petstore/java/retrofit2-play24/build.gradle b/samples/client/petstore/java/retrofit2-play24/build.gradle new file mode 100644 index 00000000000..f82ab3d19e1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/build.gradle @@ -0,0 +1,113 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + 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) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + 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-java-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + oltu_version = "1.0.1" + retrofit_version = "2.0.2" + swagger_annotations_version = "1.5.8" + junit_version = "4.12" + jodatime_version = "2.9.3" +} + +dependencies { + compile "com.squareup.retrofit2:retrofit:$retrofit_version" + compile "com.squareup.retrofit2:converter-scalars:$retrofit_version" + compile "com.squareup.retrofit2:converter-gson:$retrofit_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + compile "joda-time:joda-time:$jodatime_version" + + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit2-play24/build.sbt b/samples/client/petstore/java/retrofit2-play24/build.sbt new file mode 100644 index 00000000000..044dec41851 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/build.sbt @@ -0,0 +1,21 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-java-client", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.squareup.retrofit2" % "retrofit" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-scalars" % "2.0.2" % "compile", + "com.squareup.retrofit2" % "converter-gson" % "2.0.2" % "compile", + "io.swagger" % "swagger-annotations" % "1.5.8" % "compile", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", + "joda-time" % "joda-time" % "2.9.3" % "compile", + "junit" % "junit" % "4.12" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/retrofit2-play24/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2-play24/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..0437c4dd8cc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ + +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Animal.md b/samples/client/petstore/java/retrofit2-play24/docs/Animal.md new file mode 100644 index 00000000000..b3f325c3524 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Animal.md @@ -0,0 +1,11 @@ + +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/AnimalFarm.md b/samples/client/petstore/java/retrofit2-play24/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..77292549927 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [**List<List<BigDecimal>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..e8cc4cd36dc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ + +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | [**List<BigDecimal>**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2-play24/docs/ArrayTest.md new file mode 100644 index 00000000000..9feee16427f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ArrayTest.md @@ -0,0 +1,12 @@ + +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | [**List<List<Long>>**](List.md) | | [optional] +**arrayArrayOfModel** | [**List<List<ReadOnlyFirst>>**](List.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Cat.md b/samples/client/petstore/java/retrofit2-play24/docs/Cat.md new file mode 100644 index 00000000000..6e9f71ce7dd --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Cat.md @@ -0,0 +1,10 @@ + +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Category.md b/samples/client/petstore/java/retrofit2-play24/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ClassModel.md b/samples/client/petstore/java/retrofit2-play24/docs/ClassModel.md new file mode 100644 index 00000000000..64f880c8786 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ClassModel.md @@ -0,0 +1,10 @@ + +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Client.md b/samples/client/petstore/java/retrofit2-play24/docs/Client.md new file mode 100644 index 00000000000..5c490ea166c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Client.md @@ -0,0 +1,10 @@ + +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Dog.md b/samples/client/petstore/java/retrofit2-play24/docs/Dog.md new file mode 100644 index 00000000000..ac7cea323ff --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Dog.md @@ -0,0 +1,10 @@ + +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/EnumArrays.md b/samples/client/petstore/java/retrofit2-play24/docs/EnumArrays.md new file mode 100644 index 00000000000..4dddc0bfd27 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/EnumArrays.md @@ -0,0 +1,27 @@ + +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] +**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] + + + +## Enum: JustSymbolEnum +Name | Value +---- | ----- +GREATER_THAN_OR_EQUAL_TO | ">=" +DOLLAR | "$" + + + +## Enum: List<ArrayEnumEnum> +Name | Value +---- | ----- +FISH | "fish" +CRAB | "crab" + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/EnumClass.md b/samples/client/petstore/java/retrofit2-play24/docs/EnumClass.md new file mode 100644 index 00000000000..c746edc3cb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/EnumClass.md @@ -0,0 +1,14 @@ + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md new file mode 100644 index 00000000000..1746ccb273e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md @@ -0,0 +1,37 @@ + +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + + + +## Enum: EnumStringEnum +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + +## Enum: EnumIntegerEnum +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumNumberEnum +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md new file mode 100644 index 00000000000..bbd8da9fcc4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md @@ -0,0 +1,191 @@ +# FakeApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** fake | To test enum parameters + + + +# **testClientModel** +> Client testClientModel(body) + +To test \"client\" model + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +Client body = new Client(); // Client | client model +try { + Client result = apiInstance.testClientModel(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **testEndpointParameters** +> Void testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.FakeApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure HTTP basic authorization: http_basic_test +HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); +http_basic_test.setUsername("YOUR USERNAME"); +http_basic_test.setPassword("YOUR PASSWORD"); + +FakeApi apiInstance = new FakeApi(); +BigDecimal number = new BigDecimal(); // BigDecimal | None +Double _double = 3.4D; // Double | None +String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None +byte[] _byte = B; // byte[] | None +Integer integer = 56; // Integer | None +Integer int32 = 56; // Integer | None +Long int64 = 789L; // Long | None +Float _float = 3.4F; // Float | None +String string = "string_example"; // String | None +byte[] binary = B; // byte[] | None +LocalDate date = new LocalDate(); // LocalDate | None +DateTime dateTime = new DateTime(); // DateTime | None +String password = "password_example"; // String | None +String paramCallback = "paramCallback_example"; // String | None +try { + Void result = apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **patternWithoutDelimiter** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] + **binary** | **byte[]**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **DateTime**| None | [optional] + **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/xml; charset=utf-8application/json; charset=utf-8, + - **Accept**: application/xml; charset=utf-8, application/json; charset=utf-8 + + +# **testEnumParameters** +> Void testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble) + +To test enum parameters + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.FakeApi; + + +FakeApi apiInstance = new FakeApi(); +List enumFormStringArray = Arrays.asList("enumFormStringArray_example"); // List | Form parameter enum test (string array) +String enumFormString = "-efg"; // String | Form parameter enum test (string) +List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_example"); // List | Header parameter enum test (string array) +String enumHeaderString = "-efg"; // String | Header parameter enum test (string) +List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) +String enumQueryString = "-efg"; // String | Query parameter enum test (string) +BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) +try { + Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: */* + - **Accept**: */* + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/FormatTest.md b/samples/client/petstore/java/retrofit2-play24/docs/FormatTest.md new file mode 100644 index 00000000000..44de7d9511a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/FormatTest.md @@ -0,0 +1,22 @@ + +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | [**BigDecimal**](BigDecimal.md) | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **byte[]** | | [optional] +**date** | [**LocalDate**](LocalDate.md) | | +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**uuid** | **String** | | [optional] +**password** | **String** | | + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/retrofit2-play24/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..c1d0aac5672 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ + +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**foo** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/MapTest.md b/samples/client/petstore/java/retrofit2-play24/docs/MapTest.md new file mode 100644 index 00000000000..714a97a40d9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/MapTest.md @@ -0,0 +1,19 @@ + +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [**Map<String, Map<String, String>>**](Map.md) | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] + + + +## Enum: Map<String, InnerEnum> +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/retrofit2-play24/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..e3487bcc501 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ + +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**dateTime** | [**DateTime**](DateTime.md) | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Model200Response.md b/samples/client/petstore/java/retrofit2-play24/docs/Model200Response.md new file mode 100644 index 00000000000..5b3a9a0e46d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Model200Response.md @@ -0,0 +1,11 @@ + +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ModelApiResponse.md b/samples/client/petstore/java/retrofit2-play24/docs/ModelApiResponse.md new file mode 100644 index 00000000000..3eec8686cc9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ModelApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ModelReturn.md b/samples/client/petstore/java/retrofit2-play24/docs/ModelReturn.md new file mode 100644 index 00000000000..a679b04953e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ModelReturn.md @@ -0,0 +1,10 @@ + +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Name.md b/samples/client/petstore/java/retrofit2-play24/docs/Name.md new file mode 100644 index 00000000000..ce2fb4dee50 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Name.md @@ -0,0 +1,13 @@ + +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] +**property** | **String** | | [optional] +**_123Number** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/NumberOnly.md b/samples/client/petstore/java/retrofit2-play24/docs/NumberOnly.md new file mode 100644 index 00000000000..a3feac7fadc --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/NumberOnly.md @@ -0,0 +1,10 @@ + +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | [**BigDecimal**](BigDecimal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Order.md b/samples/client/petstore/java/retrofit2-play24/docs/Order.md new file mode 100644 index 00000000000..a1089f5384e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Order.md @@ -0,0 +1,24 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**DateTime**](DateTime.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/OuterEnum.md b/samples/client/petstore/java/retrofit2-play24/docs/OuterEnum.md new file mode 100644 index 00000000000..ed2cb206789 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/OuterEnum.md @@ -0,0 +1,14 @@ + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Pet.md b/samples/client/petstore/java/retrofit2-play24/docs/Pet.md new file mode 100644 index 00000000000..5b63109ef92 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Pet.md @@ -0,0 +1,24 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md b/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md new file mode 100644 index 00000000000..34ec23fc955 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md @@ -0,0 +1,452 @@ +# PetApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> Void addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.addPet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> Void deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + Void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("status_example"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to return +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> Void updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + Void result = apiInstance.updatePet(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> Void updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + Void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +[**Void**](.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/xml, application/json + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.PetApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure OAuth2 access token for authorization: petstore_auth +OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); +petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/ReadOnlyFirst.md b/samples/client/petstore/java/retrofit2-play24/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..426b7cde95a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ + +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/SpecialModelName.md b/samples/client/petstore/java/retrofit2-play24/docs/SpecialModelName.md new file mode 100644 index 00000000000..c2c6117c552 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/SpecialModelName.md @@ -0,0 +1,10 @@ + +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Long** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md b/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md new file mode 100644 index 00000000000..14b930e6534 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md @@ -0,0 +1,198 @@ +# StoreApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet + + + +# **deleteOrder** +> Void deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + Void result = apiInstance.deleteOrder(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.ApiClient; +//import io.swagger.client.ApiException; +//import io.swagger.client.Configuration; +//import io.swagger.client.auth.*; +//import io.swagger.client.api.StoreApi; + +ApiClient defaultClient = Configuration.getDefaultApiClient(); + +// Configure API key authorization: api_key +ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); +api_key.setApiKey("YOUR API KEY"); +// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) +//api_key.setApiKeyPrefix("Token"); + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Long orderId = 789L; // Long | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.StoreApi; + + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Tag.md b/samples/client/petstore/java/retrofit2-play24/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/User.md b/samples/client/petstore/java/retrofit2-play24/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md b/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md new file mode 100644 index 00000000000..e8adef94ea9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to ** + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user + + + +# **createUser** +> Void createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + Void result = apiInstance.createUser(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithArrayInput** +> Void createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithArrayInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **createUsersWithListInput** +> Void createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + Void result = apiInstance.createUsersWithListInput(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **deleteUser** +> Void deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + Void result = apiInstance.deleteUser(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> Void logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +try { + Void result = apiInstance.logoutUser(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updateUser** +> Void updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.ApiException; +//import io.swagger.client.api.UserApi; + + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + Void result = apiInstance.updateUser(username, body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +[**Void**](.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/java/retrofit2-play24/git_push.sh b/samples/client/petstore/java/retrofit2-play24/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/java/retrofit2-play24/gradle.properties b/samples/client/petstore/java/retrofit2-play24/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/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-play24/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..2c6137b87896c8f70315ae454e00a969ef5f6019 GIT binary patch literal 53639 zcmafaW0a=B^559DjdyI@wr$%scWm3Xy<^+Pj_sKpY&N+!|K#4>Bz;ajPk*RBjZ;RV75EK*;qpZCo(BB5~-#>pF^k0$_Qx&3rs}{XFZ)$uJU-ZpbB>L3?|knJ{J+ge{%=bI`#Yn9v&Fxx>fd=_|H)(FY-DO{ z_Wxu>{a02GXCp^PGw1(fh-I*;dGTM?mA^##pNEJ#c-Y%I7@3kW(VN&Bxw!bn$iWOU zB8BZ)vT4(}GX%q~h3EYwbR?$d6|xnvg_e@4>dl5l+%FtPbGqa`;Uk##t$#g&CK4GO zz%my0ZR1Fv@~b2_>T0cBP)ECz-Uc^nW9e+`W4!=mSJPopgoe3A(NMzBd0mR?$&3XA zRL1}bJ2Q%R#bWHrC`j_)tPKMEyHuGSpdJMhT(Ob(e9H+#=Skp%#jzj=BVvc(-RSWB z{_T`UcEeWD{z`!3-y;_N|Ljr4%f;2qPSM%n?_s%GnYsM!d3p)CxmudpyIPqTxjH!i z;}A+!>>N;pko++K5n~I7m4>yco2%Zc$59RohB(l%KcJc9s^nw^?2JGy>O4#x5+CZH zqU~7kA>WE)ngvsdfKhLUX0Lc3r+In0Uyn}LZhm?n){&LHNJws546du%pia=j zyH8CD{^Qx%kFe@kX*$B!DxLa(Y?BO32sm8%#_ynjU-m>PJbabL`~0Ai zeJm<6okftSJUd2!X(>}i#KAh-NR2!Kg%c2JD=G|T%@Q0JQzqKB)Qc4E-{ZF=#PGZg zior4-caRB-Jj;l}Xb_!)TjB`jC}})6z~3AsRE&t~CO&)g{dqM0iK;lvav8?kE1< zmCrHxDZe?&rEK7M4tG-i!`Zk-*IzSk0M0&Ul8+J>*UD(A^;bAFDcz>d&lzAlw}b## zjfu@)rAou-86EN%8_Nv;%bNUmy*<6sbgB9)ZCihdSh_VT2iGFv+T8p&Z&wO02nKtdx?eZh^=*<>SZHSn(Pv)bgn{ zb15>YnVnJ^PO025c~^uK&W1C1XTs1az44L~-9Z-fU3{VvA?T& zdpi&S`mZ|$tMuN{{i|O}fAx#*KkroHe;6z^7c*x`2Rk!a2L~HB$A4@(Rz*hvM+og( zJW+4;S-A$#+Gec-rn8}at+q5gRrNy^iU?Z4Gz_|qzS~sG_EV#m%-VW!jQ>f3jc-Vq zW;~>OqI1Th&*fx#`c^=|A4GGoDp+ZH!n0_fDo-ks3d&GlT=(qzr(?Qw`PHvo3PoU6YJE zu{35)=P`LRm@+=ziAI)7jktM6KHx*v&WHVBYp<~UtR3c?Wv_{a0(k&NF!o#+@|Y6Y z>{||-i0v8N2ntXRrVx~#Z1JMA3C2ki}OkJ4W`WjZIuLByNUEL2HqqKrbi{9a8` zk-w0I$a<6;W6&X<&EbIqul`;nvc+D~{g5al{0oOSp~ zhg;6nG1Bh-XyOBM63jb_z`7apSsta``K{!Q{}mZ!m4rTmWi^<*BN2dh#PLZ)oXIJY zl#I3@$+8Fvi)m<}lK_}7q~VN%BvT^{q~ayRA7mwHO;*r0ePSK*OFv_{`3m+96HKgt z=nD-=Pv90Ae1p)+SPLT&g(Fdqbcc(Vnk5SFyc|Tq08qS;FJ1K4rBmtns%Su=GZchE zR(^9W-y!{QfeVPBeHpaBA{TZpQ*(d$H-*GI)Y}>X2Lk&27aFkqXE7D?G_iGav2r&P zx3V=8GBGi8agj5!H?lDMr`1nYmvKZj!~0{GMPb!tM=VIJXbTk9q8JRoSPD*CH@4I+ zfG-6{Z=Yb->)MIUmXq-#;=lNCyF1G*W+tW6gdD||kQfW$J_@=Y9KmMD!(t#9-fPcJ z>%&KQC-`%E`{y^i!1u=rJP_hhGErM$GYE3Y@ZzzA2a-PC>yaoDziZT#l+y)tfyR}U z5Epq`ACY|VUVISHESM5$BpWC0FpDRK&qi?G-q%Rd8UwIq&`d(Mqa<@(fH!OfNIgFICEG?j_Gj7FS()kY^P(I!zbl`%HB z7Rx=q2vZFjy^XypORT$^NJv_`Vm7-gkJWYsN5xg>snt5%oG?w1K#l_UH<>4@d0G@3 z)r?|yba6;ksyc+5+8YZ?)NZ+ER!4fIzK>>cs^(;ib7M}asT&)+J=J@U^~ffJ>65V# zt_lyUp52t`vT&gcQ%a6Ca)p8u6v}3iJzf?zsx#e9t)-1OtqD$Mky&Lpz6_v?p0|y4 zI{Nq9z89OxQbsqX)UYj z(BGu`28f8C^e9R2jf0Turq;v+fPCWD*z8!8-Q-_s`ILgwo@mtnjpC_D$J zCz7-()9@8rQ{4qy<5;*%bvX3k$grUQ{Bt;B#w))A+7ih631uN?!_~?i^g+zO^lGK$>O1T1$6VdF~%FKR6~Px%M`ibJG*~uQ>o^r9qLo*`@^ry@KX^$LH0>NGPL%MG8|;8 z@_)h2uvB1M!qjGtZgy~7-O=GUa`&;xEFvC zwIt?+O;Fjwgn3aE%`_XfZEw5ayP+JS8x?I|V3ARbQ5@{JAl1E*5a{Ytc(UkoDKtD# zu)K4XIYno7h3)0~5&93}pMJMDr*mcYM|#(FXS@Pj)(2!cl$)R-GwwrpOW!zZ2|wN) zE|B38xr4_NBv|%_Lpnm$We<_~S{F1x42tph3PAS`0saF^PisF6EDtce+9y6jdITmu zqI-CLeTn2%I3t3z_=e=YGzUX6i5SEujY`j|=aqv#(Q=iWPkKhau@g|%#xVC2$6<{2 zAoimy5vLq6rvBo3rv&^VqtaKt_@Vx^gWN{f4^@i6H??!ra^_KC-ShWC(GBNt3o~T^ zudX<0v!;s$rIflR?~Tu4-D=%~E=glv+1|pg*ea30re-2K@8EqQ{8#WY4X-br_!qpq zL;PRCi^e~EClLpGb1MrsXCqfD2m615mt;EyR3W6XKU=4(A^gFCMMWgn#5o1~EYOH* zOlolGlD;B!j%lRFaoc)q_bOH-O!r}g1Bhlhy*dRoTf-bI%`A`kU)Q=HA9HgCKqq&A z2$_rtL-uIA7`PiJfw380j@M4Fff-?(Xe(aR`4>BZyDN2$2E7QQ1}95@X819fnA(}= za=5VF-%;l}aHSRHCfs(#Qf%dPue~fGpy7qPs*eLX2Aa0+@mPxnS4Wm8@kP7KEL)8s z@tNmawLHST-FS4h%20%lVvd zkXpxWa43E`zX{6-{2c+L9C`l(ZRG8`kO9g7t&hx?>j~5_C;y5u*Bvl79)Bq?@T7bN z=G2?QDa0J3VwCfZG0BjOFP>xz4jtv3LS>jz#1x~b9u1*n9>Y6?u8W?I^~;N{GC<1y} zc&Wz{L`kJUSt=oA=5ZHtNj3PSB%w5^=0(U7GC^zUgcdkujo>ruzyBurtTjKuNf1-+ zzn~oZFXCbR&xq&W{ar~T`@fNef5M$u^-C92HMBo=*``D8Q^ktX z(qT{_R=*EI?-R9nNUFNR#{(Qb;27bM14bjI`c#4RiinHbnS445Jy^%krK%kpE zFw%RVQd6kqsNbiBtH*#jiPu3(%}P7Vhs0G9&Dwb4E-hXO!|whZ!O$J-PU@j#;GrzN zwP9o=l~Nv}4OPvv5rVNoFN>Oj0TC%P>ykicmFOx*dyCs@7XBH|w1k2hb`|3|i^GEL zyg7PRl9eV ztQ1z)v~NwH$ebcMSKc-4D=?G^3sKVG47ZWldhR@SHCr}SwWuj5t!W$&HAA*Wo_9tM zw5vs`2clw`z@~R-#W8d4B8!rFtO}+-$-{6f_`O-^-EhGraqg%$D618&<9KG``D|Rb zQJ&TSE3cfgf8i}I^DLu+-z{{;QM>K3I9~3R9!0~=Y`A1=6`CF#XVH@MWO?3@xa6ev zdw08_9L=>3%)iXA(_CE@ipRQ{Tb+@mxoN^3ktgmt^mJ(u#=_Plt?5qMZOA3&I1&NU zOG+0XTsIkbhGsp(ApF2MphRG^)>vqagn!-%pRnppa%`-l@DLS0KUm8*e9jGT0F%0J z*-6E@Z*YyeZ{eP7DGmxQedo}^+w zM~>&E$5&SW6MxP##J56Eo@0P34XG})MLCuhMyDFf**?tziO?_Ad&Jhd z`jok^B{3ff*7cydrxYjdxX`14`S+34kW^$fxDmNn2%fsQ6+Zou0%U{3Y>L}UIbQbw z*E#{Von}~UEAL?vvihW)4?Kr-R?_?JSN?B?QzhUWj==1VNEieTMuTJ#-nl*c@qP+` zGk@aE0oAD5!9_fO=tDQAt9g0rKTr{Z0t~S#oy5?F3&aWm+igqKi| zK9W3KRS|1so|~dx%90o9+FVuN7)O@by^mL=IX_m^M87i&kT1^#9TCpI@diZ_p$uW3 zbA+-ER9vJ{ii?QIZF=cfZT3#vJEKC|BQhNd zGmxBDLEMnuc*AET~k8g-P-K+S~_(+GE9q6jyIMka(dr}(H% z$*z;JDnyI@6BQ7KGcrv03Hn(abJ_-vqS>5~m*;ZJmH$W`@csQ8ejiC8S#sYTB;AoF zXsd!kDTG#3FOo-iJJpd$C~@8}GQJ$b1A85MXp?1#dHWQu@j~i4L*LG40J}+V=&-(g zh~Hzk(l1$_y}PX}Ypluyiib0%vwSqPaJdy9EZ;?+;lFF8%Kb7cwPD17C}@N z2OF;}QCM4;CDx~d;XnunQAx5mQbL#);}H57I+uB9^v|cmZwuXGkoH-cAJ%nIjSO$E z{BpYdC9poyO5pvdL+ZPWFuK}c8WGEq-#I3myONq^BL%uG`RIoSBTEK9sAeU4UBh7f zzM$s|&NtAGN&>`lp5Ruc%qO^oL;VGnzo9A8{fQn@YoORA>qw;^n2pydq>;Ji9(sPH zLGsEeTIH?_6C3uyWoW(gkmM(RhFkiDuQPXmL7Oes(+4)YIHt+B@i`*%0KcgL&A#ua zAjb8l_tO^Ag!ai3f54t?@{aoW%&Hdst}dglRzQlS=M{O!=?l z*xY2vJ?+#!70RO8<&N^R4p+f=z z*&_e}QT%6-R5Wt66moGfvorp$yE|3=-2_(y`FnL0-7A?h%4NMZ#F#Rcb^}971t5ib zw<20w|C?HVv%|)Q)Pef8tGjwQ+!+<{>IVjr@&SRVO*PyC?Efnsq;Eq{r;U2)1+tgp z)@pZ}gJmzf{m=K@7YA_8X#XK+)F465h%z38{V-K8k%&_GF+g^s&9o6^B-&|MDFI)H zj1ofQL>W(MJLOu3xkkJZV@$}GEG~XBz~WvRjxhT0$jKKZKjuKi$rmR-al}Hb3xDL) z^xGG2?5+vUAo4I;$(JgeVQe9+e)vvJ={pO~05f|J={%dsSLVcF>@F9p4|nYK&hMua zWjNvRod}l~WmGo|LX2j#w$r$y?v^H?Gu(_?(WR_%D@1I@$yMTKqD=Ca2) zWBQmx#A$gMrHe^A8kxAgB}c2R5)14G6%HfpDf$(Di|p8ntcN;Hnk)DR1;toC9zo77 zcWb?&&3h65(bLAte%hstI9o%hZ*{y=8t$^!y2E~tz^XUY2N2NChy;EIBmf(Kl zfU~&jf*}p(r;#MP4x5dI>i`vjo`w?`9^5(vfFjmWp`Ch!2Ig}rkpS|T%g@2h-%V~R zg!*o7OZSU-%)M8D>F^|z+2F|!u1mOt?5^zG%;{^CrV^J?diz9AmF!UsO?Pl79DKvD zo-2==yjbcF5oJY!oF?g)BKmC8-v|iL6VT|Gj!Gk5yaXfhs&GeR)OkZ}=q{exBPv)& zV!QTQBMNs>QQ))>(rZOn0PK+-`|7vKvrjky3-Kmuf8uJ`x6&wsA5S(tMf=m;79Hzv za%lZ(OhM&ZUCHtM~FRd#Uk3Iy%oXe^)!Jci39D(a$51WER+%gIZYP)!}nDtDw_FgPL3e>1ilFN=M(j~V` zjOtRhOB8bX8}*FD0oy}+s@r4XQT;OFH__cEn-G#aYHpJDI4&Zo4y2>uJdbPYe zOMGMvbA6#(p00i1{t~^;RaHmgZtE@we39mFaO0r|CJ0zUk$|1Pp60Q&$A;dm>MfP# zkfdw?=^9;jsLEXsccMOi<+0-z|NZb(#wwkcO)nVxJxkF3g(OvW4`m36ytfPx5e-ujFXf($)cVOn|qt9LL zNr!InmcuVkxEg8=_;E)+`>n2Y0eAIDrklnE=T9Pyct>^4h$VDDy>}JiA=W9JE79<6 zv%hpzeJC)TGX|(gP!MGWRhJV}!fa1mcvY%jC^(tbG3QIcQnTy&8UpPPvIekWM!R?R zKQanRv+YZn%s4bqv1LBgQ1PWcEa;-MVeCk`$^FLYR~v%9b-@&M%giqnFHV;5P5_et z@R`%W>@G<6GYa=JZ)JsNMN?47)5Y3@RY`EVOPzxj;z6bn#jZv|D?Fn#$b}F!a}D9{ ztB_roYj%34c-@~ehWM_z;B{G5;udhY`rBH0|+u#!&KLdnw z;!A%tG{%Ua;}OW$BG`B#^8#K$1wX2K$m`OwL-6;hmh{aiuyTz;U|EKES= z9UsxUpT^ZZyWk0;GO;Fe=hC`kPSL&1GWS7kGX0>+votm@V-lg&OR>0*!Iay>_|5OT zF0w~t01mupvy4&HYKnrG?sOsip%=<>nK}Bxth~}g)?=Ax94l_=mC{M@`bqiKtV5vf zIP!>8I;zHdxsaVt9K?{lXCc$%kKfIwh&WM__JhsA?o$!dzxP znoRU4ZdzeN3-W{6h~QQSos{-!W@sIMaM z4o?97?W5*cL~5%q+T@>q%L{Yvw(a2l&68hI0Ra*H=ZjU!-o@3(*7hIKo?I7$gfB(Vlr!62-_R-+T;I0eiE^><*1_t|scfB{r9+a%UxP~CBr zl1!X^l01w8o(|2da~Mca)>Mn}&rF!PhsP_RIU~7)B~VwKIruwlUIlOI5-yd4ci^m{ zBT(H*GvKNt=l7a~GUco)C*2t~7>2t?;V{gJm=WNtIhm4x%KY>Rm(EC^w3uA{0^_>p zM;Na<+I<&KwZOUKM-b0y6;HRov=GeEi&CqEG9^F_GR*0RSM3ukm2c2s{)0<%{+g78 zOyKO%^P(-(U09FO!75Pg@xA{p+1$*cD!3=CgW4NO*p}&H8&K`(HL&$TH2N-bf%?JL zVEWs;@_UDD7IoM&P^(k-U?Gs*sk=bLm+f1p$ggYKeR_7W>Zz|Dl{{o*iYiB1LHq`? ztT)b^6Pgk!Kn~ozynV`O(hsUI52|g{0{cwdQ+=&@$|!y8{pvUC_a5zCemee6?E{;P zVE9;@3w92Nu9m_|x24gtm23{ST8Bp;;iJlhaiH2DVcnYqot`tv>!xiUJXFEIMMP(ZV!_onqyQtB_&x}j9 z?LXw;&z%kyYjyP8CQ6X);-QW^?P1w}&HgM}irG~pOJ()IwwaDp!i2$|_{Ggvw$-%K zp=8N>0Fv-n%W6{A8g-tu7{73N#KzURZl;sb^L*d%leKXp2Ai(ZvO96T#6*!73GqCU z&U-NB*0p@?f;m~1MUN}mfdpBS5Q-dbhZ$$OWW=?t8bT+R5^vMUy$q$xY}ABi60bb_ z9;fj~2T2Ogtg8EDNr4j96{@+9bRP#Li7YDK1Jh8|Mo%NON|bYXi~D(W8oiC2SSE#p z=yQ0EP*}Z)$K$v?MJp8s=xroI@gSp&y!De;aik!U7?>3!sup&HY{6!eElc+?ZW*|3 zjJ;Nx>Kn@)3WP`{R821FpY6p1)yeJPi6yfq=EffesCZjO$#c;p!sc8{$>M-i#@fCt zw?GQV4MTSvDH(NlD2S*g-YnxCDp*%|z9^+|HQ(#XI0Pa8-Io=pz8C&Lp?23Y5JopL z!z_O3s+AY&`HT%KO}EB73{oTar{hg)6J7*KI;_Gy%V%-oO3t+vcyZ?;&%L z3t4A%Ltf=2+f8qITmoRfolL;I__Q8Z&K9*+_f#Sue$2C;xTS@%Z*z-lOAF-+gj1C$ zKEpt`_qg;q^41dggeNsJv#n=5i+6Wyf?4P_a=>s9n(ET_K|*zvh633Mv3Xm3OE!n` zFk^y65tStyk4aamG*+=5V^UePR2e0Fbt7g$({L1SjOel~1^9SmP2zGJ)RZX(>6u4^ zQ78wF_qtS~6b+t&mKM=w&Dt=k(oWMA^e&V#&Y5dFDc>oUn+OU0guB~h3};G1;X=v+ zs_8IR_~Y}&zD^=|P;U_xMA{Ekj+lHN@_n-4)_cHNj0gY4(Lx1*NJ^z9vO>+2_lm4N zo5^}vL2G%7EiPINrH-qX77{y2c*#;|bSa~fRN2)v=)>U@;YF}9H0XR@(+=C+kT5_1 zy?ZhA&_&mTY7O~ad|LX+%+F{GTgE0K8OKaC2@NlC1{j4Co8;2vcUbGpA}+hBiDGCS zl~yxngtG}PI$M*JZYOi{Ta<*0f{3dzV0R}yIV7V>M$aX=TNPo|kS;!!LP3-kbKWj` zR;R%bSf%+AA#LMkG$-o88&k4bF-uIO1_OrXb%uFp((Pkvl@nVyI&^-r5p}XQh`9wL zKWA0SMJ9X|rBICxLwhS6gCTVUGjH&)@nofEcSJ-t4LTj&#NETb#Z;1xu(_?NV@3WH z;c(@t$2zlY@$o5Gy1&pvja&AM`YXr3aFK|wc+u?%JGHLRM$J2vKN~}5@!jdKBlA>;10A(*-o2>n_hIQ7&>E>TKcQoWhx7um zx+JKx)mAsP3Kg{Prb(Z7b};vw&>Tl_WN)E^Ew#Ro{-Otsclp%Ud%bb`8?%r>kLpjh z@2<($JO9+%V+To>{K?m76vT>8qAxhypYw;Yl^JH@v9^QeU01$3lyvRt^C#(Kr#1&2 ziOa@LG9p6O=jO6YCVm-d1OB+_c858dtHm>!h6DUQ zj?dKJvwa2OUJ@qv4!>l1I?bS$Rj zdUU&mofGqgLqZ2jGREYM>;ubg@~XE>T~B)9tM*t-GmFJLO%^tMWh-iWD9tiYqN>eZ zuCTF%GahsUr#3r3I5D*SaA75=3lfE!SpchB~1Xk>a7Ik!R%vTAqhO z#H?Q}PPN8~@>ZQ^rAm^I=*z>a(M4Hxj+BKrRjJcRr42J@DkVoLhUeVWjEI~+)UCRs zja$08$Ff@s9!r47##j1A5^B6br{<%L5uW&8t%_te(t@c|4Fane;UzM{jKhXfC zQa|k^)d*t}!<)K)(nnDxQh+Q?e@YftzoGIIG?V?~$cDY_;kPF>N}C9u7YcZzjzc7t zx3Xi|M5m@PioC>dCO$ia&r=5ZLdGE8PXlgab`D}>z`dy(+;Q%tz^^s*@5D)gll+QL z6@O3@K6&zrhitg~{t*EQ>-YN zy&k{89XF*^mdeRJp{#;EAFi_U<7}|>dl^*QFg**9wzlA#N9!`Qnc68+XRbO-Za=t zy@wz`mi0MmgE?4b>L$q&!%B!6MC7JjyG#Qvwj{d8)bdF`hA`LWSv+lBIs(3~hKSQ^0Se!@QOt;z5`!;Wjy1l8w=(|6%GPeK)b)2&Ula zoJ#7UYiJf>EDwi%YFd4u5wo;2_gb`)QdsyTm-zIX954I&vLMw&_@qLHd?I~=2X}%1 zcd?XuDYM)(2^~9!3z)1@hrW`%-TcpKB1^;IEbz=d0hv4+jtH;wX~%=2q7YW^C67Fk zyxhyP=Au*oC7n_O>l)aQgISa=B$Be8x3eCv5vzC%fSCn|h2H#0`+P1D*PPuPJ!7Hs z{6WlvyS?!zF-KfiP31)E&xYs<)C03BT)N6YQYR*Be?;bPp>h?%RAeQ7@N?;|sEoQ% z4FbO`m}Ae_S79!jErpzDJ)d`-!A8BZ+ASx>I%lITl;$st<;keU6oXJgVi?CJUCotEY>)blbj&;Qh zN*IKSe7UpxWPOCl1!d0I*VjT?k6n3opl8el=lonT&1Xt8T{(7rpV(?%jE~nEAx_mK z2x=-+Sl-h<%IAsBz1ciQ_jr9+nX57O=bO_%VtCzheWyA}*Sw!kN-S9_+tM}G?KEqqx1H036ELVw3Ja0!*Kr-Qo>)t*?aj2$x;CajQ@t`vbVbNp1Oczu@ zIKB+{5l$S;n(ny4#$RSd#g$@+V+qpAU&pBORg2o@QMHYLxS;zGOPnTA`lURgS{%VA zujqnT8gx7vw18%wg2)A>Kn|F{yCToqC2%)srDX&HV#^`^CyAG4XBxu7QNb(Ngc)kN zPoAhkoqR;4KUlU%%|t2D8CYQ2tS2|N#4ya9zsd~cIR=9X1m~a zq1vs3Y@UjgzTk#$YOubL*)YvaAO`Tw+x8GwYPEqbiAH~JNB?Q@9k{nAuAbv)M=kKn zMgOOeEKdf8OTO|`sVCnx_UqR>pFDlXMXG*KdhoM9NRiwYgkFg7%1%0B2UWn_9{BBW zi(Ynp7L|1~Djhg=G&K=N`~Bgoz}Bu0TR6WsI&MC@&)~>7%@S4zHRZxEpO(sp7d)R- zTm)))1Z^NHOYIU?+b2HZL0u1k>{4VGqQJAQ(V6y6+O+>ftKzA`v~wyV{?_@hx>Wy# zE(L|zidSHTux00of7+wJ4YHnk%)G~x)Cq^7ADk{S-wSpBiR2u~n=gpqG~f=6Uc7^N zxd$7)6Cro%?=xyF>PL6z&$ik^I_QIRx<=gRAS8P$G0YnY@PvBt$7&%M`ao@XGWvuE zi5mkN_5kYHJCgC;f_Ho&!s%CF7`#|B`tbUp4>88a8m$kE_O+i@pmEOT*_r0PhCjRvYxN*d5+w5 z<+S)w+1pvfxU6u{0}0sknRj8t^$uf?FCLg<%7SQ-gR~Y6u|f!Abx5U{*KyZ8o(S{G znhQx#Zs_b8jEk`5jd9CUYo>05&e69Ys&-x_*|!PoX$msbdBEGgPSpIl93~>ndH;t5 z?g>S+H^$HtoWcj4>WYo*Gu;Y#8LcoaP!HO?SFS&F9TkZnX`WBhh2jea0Vy%vVx~36 z-!7X*!Tw{Zdsl3qOsK&lf!nnI(lud){Cp$j$@cKrIh@#?+cEyC*m$8tnZIbhG~Zb8 z95)0Fa=3ddJQjW)9W+G{80kq`gZT`XNM=8eTkr^fzdU%d5p>J}v#h&h$)O+oYYaiC z7~hr4Q0PtTg(Xne6E%E@0lhv-CW^o0@EI3>0ZbxAwd2Q zkaU2c{THdFUnut_q0l+0DpJ5KMWNTa^i@v%r`~}fxdmmVFzq6{%vbv?MJ+Q86h6qf zKiGz6Vrb>!7)}8~9}bEy^#HSP)Z^_vqKg2tAfO^GWSN3hV4YzUz)N3m`%I&UEux{a z>>tz9rJBg(&!@S9o5=M@E&|@v2N+w+??UBa3)CDVmgO9(CkCr+a1(#edYE( z7=AAYEV$R1hHyNrAbMnG^0>@S_nLgY&p9vv_XH7|y*X)!GnkY0Fc_(e)0~)Y5B0?S zO)wZqg+nr7PiYMe}!Rb@(l zV=3>ZI(0z_siWqdi(P_*0k&+_l5k``E8WC(s`@v6N3tCfOjJkZ3E2+js++(KEL|!7 z6JZg>9o=$0`A#$_E(Rn7Q78lD1>F}$MhL@|()$cYY`aSA3FK&;&tk3-Fn$m?|G11= z8+AqH86^TNcY64-<)aD>Edj$nbSh>V#yTIi)@m1b2n%j-NCQ51$9C^L6pt|!FCI>S z>LoMC0n<0)p?dWQRLwQC%6wI02x4wAos$QHQ-;4>dBqO9*-d+<429tbfq7d4!Bz~A zw@R_I;~C=vgM@4fK?a|@=Zkm=3H1<#sg`7IM7zB#6JKC*lUC)sA&P)nfwMko15q^^TlLnl5fY75&oPQ4IH{}dT3fc% z!h+Ty;cx9$M$}mW~k$k(($-MeP_DwDJ zXi|*ZdNa$(kiU?}x0*G^XK!i{P4vJzF|aR+T{)yA8LBH!cMjJGpt~YNM$%jK0HK@r z-Au8gN>$8)y;2q-NU&vH`htwS%|ypsMWjg@&jytzR(I|Tx_0(w74iE~aGx%A^s*&- zk#_zHpF8|67{l$Xc;OU^XI`QB5XTUxen~bSmAL6J;tvJSkCU0gM3d#(oWW$IfQXE{ zn3IEWgD|FFf_r2i$iY`bA~B0m zA9y069nq|>2M~U#o)a3V_J?v!I5Y|FZVrj|IbzwDCPTFEP<}#;MDK$4+z+?k5&t!TFS*)Iw)D3Ij}!|C2=Jft4F4=K74tMRar>_~W~mxphIne& zf8?4b?Aez>?UUN5sA$RU7H7n!cG5_tRB*;uY!|bNRwr&)wbrjfH#P{MU;qH>B0Lf_ zQL)-~p>v4Hz#@zh+}jWS`$15LyVn_6_U0`+_<*bI*WTCO+c&>4pO0TIhypN%y(kYy zbpG4O13DpqpSk|q=%UyN5QY2pTAgF@?ck2}gbs*@_?{L>=p77^(s)ltdP1s4hTvR# zbVEL-oMb~j$4?)op8XBJM1hEtuOdwkMwxzOf!Oc63_}v2ZyCOX3D-l+QxJ?adyrSiIJ$W&@WV>oH&K3-1w<073L3DpnPP)xVQVzJG{i)57QSd0e;Nk z4Nk0qcUDTVj@R-&%Z>&u6)a5x3E!|b;-$@ezGJ?J9L zJ#_Lt*u#&vpp2IxBL7fA$a~aJ*1&wKioHc#eC(TR9Q<>9ymdbA?RFnaPsa)iPg7Z; zid$y8`qji`WmJ5nDcKSVb}G$9yOPDUv?h1UiI_S=v%J8%S<83{;qMd0({c8>lc=7V zv$okC+*w{557!ohpAUMyBHhKLAwzs&D11ENhrvr_OtsnS!U{B+CmDH-C=+po+uSqt z+WVVXl8fKe5iCZoP;>}4OVen6_|uw8*ff-r;)O2W+6p7BPT7sT<|Qv=6lgV#3`Ch${(-Wy#6NA$YanDSFV_3aa=PAn%l@^l(XxVdh!TyFFE&->QRkk@GKyy( zC3N%PhyJf^y9iSI;o|)q9U-;Akk>;M>C8E6=3T!vc?1( zyKE(2vV5X_-HDSB2>a6LR9MvCfda}}+bZ>X z+S(fTl)S})HZM`YM`uzRw>!i~X71Kb^FnwAlOM;!g_+l~ri;+f44XrdZb4Lj% zLnTNWm+yi8c7CSidV%@Y+C$j{{Yom*(15277jE z9jJKoT4E%31A+HcljnWqvFsatET*zaYtpHAWtF|1s_}q8!<94D>pAzlt1KT6*zLQF z+QCva$ffV8NM}D4kPEFY+viR{G!wCcp_=a#|l?MwO^f4^EqV7OCWWFn3rmjW=&X+g|Pp(!m2b#9mg zf|*G(z#%g%U^ET)RCAU^ki|7_Do17Ada$cv$~( zHG#hw*H+aJSX`fwUs+fCgF0bc3Yz3eQqR@qIogSt10 znM-VrdE@vOy!0O4tT{+7Ds-+4yp}DT-60aRoqOe@?ZqeW1xR{Vf(S+~+JYGJ&R1-*anVaMt_zSKsob;XbReSb02#(OZ z#D3Aev@!944qL=76Ns-<0PJ;dXn&sw6vB9Wte1{(ah0OPDEDY9J!WVsm`axr_=>uc zQRIf|m;>km2Ivs`a<#Kq@8qn&IeDumS6!2y$8=YgK;QNDcTU}8B zepl6erp@*v{>?ixmx1RS_1rkQC<(hHfN%u_tsNcRo^O<2n71wFlb-^F2vLUoIfB|Hjxm#aY&*+um7eR@%00 zR;6vT(zb2ewr$(CwbHgKRf#X(?%wBgzk8qWw=d@1x>$40h?wIUG2;Jxys__b)vnPF z{VWvLyXGjG4LRo}MH@AP-GOti6rPu^F04vaIukReB|8<7&5cebX<)Zk(VysCOLBuL zW9pEvRa--4vwT?k6P??+#lGMUYE;EsaU~=i_|j!1qCVS_UjMVhKT%CuovR;6*~rP0)s5eX zxVhGZv+qtpZ{_FDf9p{m`ravh=h>mPMVR7J-U@%MaAOU2eY@`s-M3Oi>oRtT?Y&9o({nn~qU4FaEq|l^qnkXer)Cf0IZw;GaBt)}EIen=1lqeg zAHD~nbloktsjFh&*2iYVZ=l1yo%{RK#rgTg8a2WRS8>kl03$CS(p3}E-18`!UpyOg zcH=`UYwn0b@K1`E&aQ%*riO|F-hq;S;kE7UwYd~Ox(u)>VyaE7DA6h_V3_kW2vAR} zBZi_RC*l3!t;JPD;<*z1FiZt;=KK-xuZ`j>?c5oxC^E2R=d`f68!-X=Xw2ONC@;@V zu|Svg4StiAD$#wGarWU~exyzzchb#8=V6F<6*nAca@x}!zXN}k1t78xaOX1yloahl zC4{Ifib;g}#xqD)@Jej<+wsP+JlAn)&WO=qSu>9eKRnm6IOjwOiU=bzd;3R{^cl5* zc9kR~Gd9x`Q$_G^uwc4T9JQhvz3~XG+XpwCgz98Z>Pez=J{DD)((r(!ICFKrmR-;} zL^`7lPsSmZT?p&QpVY&Ps~!n($zaAM8X@%z!}!>;B|CbIl!Y={$prE7WS)cgB{?+| zFnW-KRB-9zM5!L+t{e~B$5lu-N8Yvbu<+|l;OcJH_P;}LdB~2?zAK67?L8YvX})BM zW1=g!&!aNylEkx#95zN~R=D=_+g^bvi(`m0Cxv2EiSJ>&ruObdT4&wfCLa2Vm*a{H z8w@~1h9cs&FqyLbv7}{R)aH=Bo80E3&u_CAxNMrTy_$&cgxR10Gj9c7F~{hm#j+lj z#){r0Qz?MaCV}f2TyRvb=Eh|GNa8M(rqpMPVxnYugYHqe!G`M@x(;>F%H46LGM_cU z{*0k6-F!7r3;j{KOaDxrV16WUIiFAfcx?^t*}ca4B8!-d?R|$UxwV8tyHdKL zhx;7%0Zn#qtx;S)REtEP-meAlV8*1qGFbRJ*eeX&+hsiLF*g9%r0Zl`L^Kn`4I)ul z32#3pg6Mu$LEI@hssUb?T$di_z zHgaB3zw;*0Lnzo$a~T_cFT&y%rdb*kR`|6opI#Pbq~F%t%*KnyUNu|G?-I#~C=i#L zEfu}ckXK+#bWo11e+-E$oobK=nX!q;YZhp}LSm6&Qe-w0XCN{-KL}l?AOUNppM-)A zyTRT@xvO=k&Zj|3XKebEPKZrJDrta?GFKYrlpnSt zA8VzCoU+3vT$%E;kH)pzIV7ZD6MIRB#w`0dViS6g^&rI_mEQjP!m=f>u=Hd04PU^cb>f|JhZ19Vl zkx66rj+G-*9z{b6?PBfYnZ4m6(y*&kN`VB?SiqFiJ#@hegDUqAh4f!+AXW*NgLQGs z>XrzVFqg&m>FT^*5DAgmMCMuFkN4y*!rK^eevG!HFvs7nC672ACBBu5h(+#G@{0J- zPLsJ{ohQEr2N|PmEHw9 znQ`qe-xyv93I;Ym=WnoVU8dau&S^(*Wp=}PSGw;&DtaKz-);y)zjD|@-RT`*6nowj z7B%)h3>Lro-}5THC@BLymuL&3~kh8M}ZrZGtYKAmrT^cym$^O!$eeK$q5X2JF1w5a}4Z6yJ<=8&J?(m6U?;+ z{+*B;P@yGffMz;OSfm7NDhkGR5|7&~FNvel8Yj{F!DWnHG>%?ReZ$1w5I$Bt_u|4v z-ow>!SF!pCGrD&K8=-<;Gp@oB<@9C&%>vPHrp4sQEJj2FdedjC=0FqD>EG?NCf=KQKVd^stDZP7KNCAP-uEO*!?vgwvdp&Dm3h5Cldn!cIOL@u>1!HSfK+~kn-9Ekr|MWNApAJCJ5&5#izmjm z$CI|Boo@;O?Z(Bo9ejP>bbH|jRKn7W3y0L1!O6v$RUtt;%5R#**`+39c$JuO`SMU+ zbzu$7Eu`JQ+ri_ap{w(R_juHcw0X8~e$48TzBX%Yd+HkSSYt2){)+rYm48G^^G#W* zFiC0%tJs0q3%fX_Mt8A=!ODeM?}KLDt@ot6_%aAdLgJ7jCqh_1O`#DT`IGhP2LIMhF* z=l?}r%Tl#)!CpcItYE2!^N8bo`z9X(%0NK9Dgg^cA|rsz?aR+dD6=;#tvNhT5W}1; zFG@_F2cO&7Pdp1;lJ8?TYlI(VI8nbx_FIGRX^Z(d zyWyJi58uPgr>8w$ugIGhX1kr*po@^F>fntO1j&ocjyK za8Z*GGvQt+q~@R@Y=LdQt&v=8-&4WOU^_-YOuT9Fx-H7c;7%(nzWD(B%>dgQ^ zU6~0sR24(ANJ?U>HZ#m8%EmD1X{uL{igUzdbi+JN=G9t`kZMGk!iLCQQiVMhOP&(*~gU(d+&V4$(z=>4zqh(GX+9C&;~g2 z9K2$`gyTRJpG_)fYq=9sG^1I{*I=s%0NX^}8!mJVc?y$OYM^n!x(2jw$$;}n&dh%D;St+FA;eW=+28j#G^YLi@Gdk*H#r-#6u?7sF7#_pv?WS^K7feY1F^;!;$rgU%J zS$lZ(hmo$F>zg$V^`25cS|=QKO1Qj((VZ;&RB*9tS;OXa7 zy(n<$4O;q>q5{{H>n}1-PoFt;=5Ap+$K8LoiaJV7w8Gb%y5icLxGD~6=6hgYQv`ZI z2Opn57nS-1{bJUr(syi^;dv+XcX8?rQRLbhfk1py8M(gkz{TH#=lTd;K=dr!mwk2s z#XnC){9$x)tjD0cUQ90|hE2BkJ9+_tIVobRGD6OQ-uKJ#4fQy!4P;tSC6Az)q?c>E zXt(59YUKD?U}Ssn(3hs&fD$i3I*L_Et-%lx%HDe%#|)*q+ZM-v%Ds3u1LPpPKe-q} zc!9Rt)FvptekA2s+NXxF7I;sH1CNPpN@RT+-*|6h*ZWL{jgu9vth{q)u=E<7D(F06 zN~UUfzhsK)`=W%Z-vr#IIVwmdb(q7k+FX-lciYO%NE!xl25SV53Hwdql-3>8y5X1U zWa3_Qfp2Z;jVX+N+1?`(dx-EJL)%oQsI0G3S=ad&v{dzNal~flHvq(0HjY!v;oE>n z4gQSa2FdJI52Weu$+lED4VYSW;D`5Zn`C#@7Hxa1Ls*#TLBjje(%NYFF+4uOc~dK! zlnyxE4NWVz0c8yx`=sP2t)fHW(PPKZPp{SCwT-on2sEM9tyGO4AW7|R;Iw5|n1KpV zR^S>`h}rxcNv2u+7H6rCvMLMV3p*H#WcN}}t0@Us{w}{20i<-v> zyos+Ev_>@CA**@JrZ6Jzm=pWd6ys`c!7-@jf<~3;!|A_`221MFp-IPg28ABf6kj-Y#eaRcQ!t!|0SRtkQK^pz;YiTC@@lJ4MDpI(++=}nTC zRb4Ak&K16t*d-P(s5zPs+vbqk1u>e5Y&a!;cO(x;E4A4}_Cgp_VoIFwhA z-o^7)=BRYu)zLT8>-5os4@Ss8R&I^?#p?bY1H-c;$NNdXK%RNCJHh)2LhC?B9yL2y z(P-1t9f~NV0_bQ{4zF|-e^9LG9qqevchug76wtFn95+@{PtD)XESnR2u}QuG0jYoh z0df4#&dz_FStgOPG0?LVGW&{znCUzHU%*b1f~F+)7aefg7_j76Vb|2WuG#1oYH_~4 zrzy#g1WMQ#gof`)Ar((3)4m3mARX~3(Ij=>-BC zR@&7dF70|)q>tI$wIr?&;>+!pE`i6CkomA1zEb&JOkmg9!>#z-nB{%!&T@S-2@Q)9 z)ekri>9QUuaHM{bWu&pZ+3|z@e2YjVG^?8F$0qad4oO9UI|R~2)ujGKZiX)9P2;pk z-kPg%FQ23x*$PhgM_1uIBbuz3YC z#9Rz(hzqTU{b28?PeO)PZWzB~VXM5)*}eUt_|uff_A8M4v&@iY{kshk{7dHX1vgHs zC%vd9vD^c;%!7NNz=JX9Q{?$~G@6h!`N>72MR*!Q{xE7IV*?trmw>3qWCP*?>qb01 zqe|3!Y0nv7sp|Md9c z4J5EJA%TD-;emh%|L2kLpA^g>)i56v6HIU8h7M+KSWYw~HHz3`ILj*{==jD(l33>r zmOdINZ8^Jo?ll^~q@{^5l#*3f`ETncJmo?iRLz*=W=o3MJ!K^xjVcw*H}p63#p4XX z1)|C%{Y&)IpRIk5oMVsUi6oyKAFy8MH$@|Zpjr^lxlMX3O{0AZTjc{gso{KRuo30V zUJxq2K=_CwV*Qx_D!hJCBTuQ}5oMNrWUBNVaa8zyMg5lrXgv8Zw@rm5NAcFplYa>P zmUNB>EB|r?#Z!Gq^`(HZl__UJ*K5 z=>`{UTlt0;Y+LmP1Wb19IWK(SIWDrqh=+K81c`t@BCS|2#@K0u5eEwQ7CG92=Axx4 zQ?CPaVE5!XY`2r!Ce@m(tRtB=&+c>a09WzP-Ys!~i;V0hEq}PU8n1a;bVbJ17rYW1 zjz|KkLZoO7-S6oQp_ocIzS43P@CJJxQ$k;$!fS3*V)m|VtBIEgCtU@W`AG9VMU_d znB-Zs3I)I(Wg=xj)Wcx03h}U3i5{D@*udPLg?Jx7dp&KEIwJiW=eh}Ps#FxbsS?F}7z<;<5RP6-UAD+_An$s3y-JAC zh{JlAX3e^CDJl1gJDbH`e=hD88ER_6+Mw8CwK&^|$BnzA|AvDV`#xF^z9b6iWb)0@ z+gir=oSUaVcJi%1k+9!pd`(3|h~4}!NM7NHPNV6rI(W4~Ie5 zl@(Xg2`OSq|HJRUg3qgr-c!}9@W?pEJXKtxP7f(aE2Es33gRSu#~XiCIpV-J;JLM{(@qK2wEvsi@6-9(cyXX!6YS0n7;TK0Ldf*JGmlvrF0 zGQ+Z509rmWa)O}r`z2W3!6u{^ZQrY`KR#VlTRmllG2v$R!7%B~IU@XnNi!E1qM$J8 z%{XFU4vy_*M0tKjDY3E*7N!d%&vnx5qr#=!IKWZfoRo8j=7ji1{xW?g^)A|7 zaaA5Rg6rwCF?y33Kz-90z!ze`@5N916S)(fHPa>{F`UEF8N5PTNjbo)PF5W_YLB*# z?o`qxQTIzokhSdBa1QGmn9b;O#g}y_4d*j*j`cx^bk(=%QwiFxlAhFSNhO0$g|ue> zDh=p|hUow5Knbclx8V;+^H6N_GHwOi!S>Qxv&}FeG-?F7bbOWud`NCE6Tv-~ud&PS6 z;F*l>WT4zvv39&RTmCZQLE67$bwxRykz(UkGzx}(C23?iLR}S-43{WT80c$J*Q`XT zVy-3mu&#j}wp^p0G%NAiIVP2_PN{*!R%t7*IJBVvWVD#wxNRyF9aXsIAl)YpxfQr$d%Rt20U@UE}@w?|8^FMT%k36 zcGi_Mw+vMvA@#}0SfIiy0KEKwQ|`iR++|PF2;LtiH7ea($I{z z32QPp-FlEQ**K_A@OC943z`Qy7wC~&v z*a`z;(`5(e#M|qb4bkN6sWR_|(7W~8<)GnX)cJAt``gu8gqP(AheO-SjJMYlQsGs0 z!;RBZwy>bfw)!(Abmna(pwAh^-;&+#$vChUEXs5QOQi8TZfgQHK$tspm+rc%ee0gy zjTq5y20IJ`i{ogd8l?~8Sbt^R_6Fx*!n6~Jl#rIt@w@qu2eHeyEKhrzqLtEPdFrzy z9*I^6dIZ z)8Gdw1V^@xGue9trS?=(#e5(O#tCJv9fRvP=`a{mnOTboq<-W$-ES7)!Xhi*#}R#6 zS&7hR(QeUetr=$Pt6uV%N&}tC;(iKI>U!y$j6RW&%@8W|29wXe@~{QlQ0OjzS;_>q z(B!=A71r|@CmR7eWdu9n0;OJ zP@VOOo#T+N$s{`3m`3Li+HA4owg&>YqCwsA5|E$b;J&v#6RbT$D!x$Yaflo92wU?A zvgD8g(aY`g7}Y2^2i31ocm&k9Km`NQipEsjU>MuRzD35*Jk7^Q(O;M32!gt1cEB@- zBOHd@@Qo{fQ^7o{FiNdS)_vTiP8toqZ`iNi^1-4(hp+s751}Tf34b z_UYQ1q0~*jIp9pRIpI8ue}$|~uu0#p>-y8t{yEwB(8yAjMXrJ{`{rp7*-wlh8&bso zHV`LnAF7Bw+w}Wm9ii3U@lEvcc-i$0&h+eUmlQuREzg!ao)ZjwThhqIKA})}akyX7 zcbuIw9K}9aUZ;hvAxk~rqpk?bYMWr-@b-pMTR8))ggQa$kBv=IinobKCR0?S&g*+Al2J`VR7he{}0Pu zae7LYa!OoTOk8?ma)M@Ta%NxQacV~KMw&)}fkmF7wvmagnTbWo))`Kofr)`-pNe99 zMnam7vRRs5LTXHWNqTzhfQo90dTdg<=@9teXaX2tyziuRI?UOxKZ5fmd%yNGf%Kis zEDdSxjSP&;Y#smYU$Dk>Sr0J42D)@hAo|7QaAGz(Qp*{d%{I-#UsBYP2*yY8d0&$4 zI^(l62Q-y4>!>S{ zn;iO%>={D42;(0h@P{>EZnIzpFV|^F%-OJADQz(1GpUqqg#t!*i zcK}eD_qV$RmK}-y_}f$Xy7B+hY~f4s{iCD7zq%C|SepGu`+>h6TI}dUGS3%oOYsZ0 z#rWTU&aeMhM%=(r(8kK@3rr|wW^MFE;dK5&^Z!>`JV{CWi^Gq?3jz~C-5hFFwLJ@e zSm3z9mnI+vIcF+RjyOL!VuZP3rJDjPSm4vYolnm)H;BIz!?dLyE0^5(pm)5*>2clW zaI^*Z;p6iGZW~Gr0(Eh+%8Jkz{S9{}=}Ewi6W0wF3|BbVb?CR2x>4xST?woP;Mz8L zDfs+0L9ga3jcM)zCC=`-ah9#oulxt9bZq9zH*fJK$bhT=%(2bPMY~}cPfTyE{_4p+ zc}3pPX`B04z+T>XwRQ4$(`U~037JrmN`)3F8vu_OcBE}M&B;1Vd%|I|1tni?f_b&$ z5wpdJ6F*oif)r=IzB$ytT72GuZi$y>H0p_#amQcJLZ^4KZySOUrRyXy3A2(i=$zB9 znZnGFLC34k?N@s@`)u8aZN({9Hfe}|^@Xk(TmCqNBR*Bter>opM!SGiDU8ShK6FNp zvod~z>Tj!GOXB^#R>6}_D@j67f5cNc#P;yMV}`S*A_OmXk_BIq3I$C}3M~aPU)agY zWC+0JA-)}O@e4XTtjzen&g=J0GIVNjG`_gS6ErXj3cGxeDN*4xEk0PNzfzO@6gb&N zB$S-WV-@efQWs%UX$AVjFN5M@8U>+?Mcqg?@=Z-R`~n~;mQGVJT_vBL|3^fHxZ?#T zE(Sd`8%2WHG)TcNaCHmv_Id%D+K}H3s&c`bxKs(_ScZzyCTpvU zHv~yhtKF9G{s+GC*7>_D@F+qEq@YmXiKTV(j#X7^?WpvIg!Yxi6uBAhh7<91{8vFL zfT?Y~vwmE;(WOL!V5Ag&#@U$mP~T=*#_ ze#QynX>tO#4IJqSj^UB>8ubSEn>Nk!Z?jZE01CJCYuY`1S3 zf%2eyXaWoAQUw)KYO;wi<&+R3_7E%h(7F?xq!8l>!^3Jqj_tNPrG= z+y2S-0j;(AilOo;>SCQu#;Cn?y4Eu za`??!yHz)qFH1Z(3KMqgn+B$&t+5s0zY|}<1kB^Q8FEAumh;^;Yr~amTx1K2%2JUk z@7uIE&0DVch|1R=ro5rjr)w!iU{_09PqfhnGqhAN^$^oz#wVNdTRQ!8^nF};4);Jz#=dTBTMMW7icnZ$dK1E0UEgP4&DNk9MFoKOhtAkVUR`d_vc!x zc|1mY&%{PBxepp^JPHmFDBQ8t@DD-3!C)-ZhGJt)?{)^0MvC%RzI;4}>XoOUF;6~j z{S20Ra%PaiGvM$pFbH;N6)b1J(N;{+Gp^^Qk34JAuPKH}Ap}fen!WlC5vrQ0$pnyq z5poi8VG>>PnGw2^-CY3XdG3<;|0xU}#WBPqn{mO=z0RwL=MXn3=;oA(1C@V^6F;ogwB4EBUpltu=)(MC@To2kSPbL zDdGz|C<@`&!MmQ*e>H>2Qkwa~K%;yZw;SnM<=qwNHu-Dh$r(}-d}T}u!=UOAkzvEOiZ6>{)t$$# zlAmjO$1)&1Zh^zdh8uhmZ>OBA1T4%s9Jex_y4|ifY_=XoX6UzpP;MuC5su(6%;)NI z4d#4aW<*)L6o7w?MY2+jRx6-3S4i zC(~)A`|)5(s?)pBvTfYjwvr@Z-Dx-F7uq}z#WJB6&}0TIi6sGXFWOxD!As%cUg)_A zI)sRCf-5kPBU|rVm0A{!s=W2){AJwvShr6Tsvbg|NrXi!7zoMde_n>-+XFX0fiQy~ zjRp|;6~pR()0a>ETtC7mZD|i$Emj!r-gq!yhAFdV1uR*M<4O?t83N1JRT~8Cy8Vha z+STlcw&CoCJt$k^#ar+~DBmvtC5tr{(>|W6wHq*NSE!^#8*rs>!oYj%fl9~Nu*d4t zdk!|mGJehKW8xJE5ZOcHRfp4plI+l1Pct;rK={=P`YH8&1hNW*YE)4yF2@wa7JFaL zLHJH6ZWc1j|nQ55Znh#>tV`!~N7lY_05Cq%|8I-yN}yf@EzDG zBL z(b0sjh+ui^*s(rg)=l8fU<%cPfba<7y?>}j3R83$2KHzWbVF*`!x^V8JY`D0itC?ZSTYH|w3lUD#$5G$@!v(Lphex2O1;%>w;Qh$t7YF3EjFuySPC$>~%EspW}@Ctn1Bghd5*HVJ=tZK~8oMiZ@9IxfFLSk~>p9cT9gOSPLyP!^bOah`U-6{}C_ zmyhS7S_-tYDm|9C6(Wu2Qe=*g5@{**z@#Ekz3Y{o7fw!^4z$yi z&=a^zmtOpsRO0lFr&c=khr)cL2v9LFKXRDdE}tWlOgpR%}oWHCeJ4;(9U_HeJYl! zwz$p|t6?#eCju@0{IF0gbk>So3C{Ror~JTpuOW!G@^?lBVrf zf?%rDK2E3x=xGC)J_lEk{(ESh-Uw*#k-n4l42f3oC3BJX0-2NMZo?P)-6y1v+?|+< zfFHX8(bw;H@;6K!?=!B#eZrkowcdn7)roPT=WM@MK?>T-cUa$oQdYp&3YRdWu~rhA z@rZKmqj8Ftz-*@`&iH|) zC(H;QiqYx4{Mz@rm`qs~*Ue~4EHM^J7i{QnL~t)O)tnwIQC;23p}TBoc=9rcuS!cQ zQgl)_F@t9{c)ESLtAcg1AbCXqVS%i1ZZRiy$*?Bu=r2ad13e|ZeWV=3pSL>YAk>X& zQZAY4kJD`CYrK-nNti&;uJ*e{cRILOFk@z?B@fNO(exjUhf!b=yuC`@(RS#ko1HA+ zOwsym7?F)}ufcD5&IV+qr+i7Mo3)6M2oI)*3?@-%ah^0rL#0PIn}XmOTP9Xsg5C;t zqkFe6yT##_ZG5KuhVQY)89LfWOeXpXVNWX2PmiRqq<$C!<^WlyO~Q=pk${$DsWY-7 zZ->4<+c@KPgKzKosGPF+&Q*>L>WaN6_FC~SP~3gH7bvg6>QgPzp`&QTpf3W>HjxDxj!y zZb`O;&XZzI2YJ4!^Mq5~Vz7lLv`StN|TSP@jdF}@9;ql?u*#Q+_E}~hak(3B%AQNq)t7PKgAWTYp>EJz^VIj67KcZ3^vvZ7{b;; zcOOArcAw2$T+$UwIib|pt3i#NAuP#3?Z@Oaz?Mt(H&u7HZu!03kV7`t5IRcf7hwck zf{Ujp*YsH;dvcW0q|=o$;z#Cg52;n5t1phY44To!sQ99h`iVzXd+v(L%?A$Ks|Ne; z7fby7IVUXqN8gzsnL-s?uIv>=Qh!qAxoe{fRaI&EcSGCTdggq-Qq?DU%SBOummO5cRa9NW}V>A0IH#pxch)!$2p8=^-XYjsB%$S$U5nI zlJEMBb!BZ_O4@87cEYUBH7}Y_MF$+(~gdf-!7)D-D)+O{*18TC{HGZFF+`%IPcmK{O{YxR> zSfJHSeQCChuPUAWe_x~gy*f!!wvt_tL-Dp=nUm+juu;4L6N1IIG4dsVMat#T^p7p1n*Tx2a!YaivBTqLsSJAF=kJej?@QWf)Y-8Ks>WkC456{B#hW-ML zI+f23(}F=MeSdbWQ>R98TOzv#Haw}ua+17H=P5|~#BDmoEPkzl#lBTvCoyj`XU|IS zHn?dXbq>rqUW8^kQN01zL~6!Vxn4!$Pu|F&#XbiF{{>T z)&khW&2Y?d8^jC|phWKQ4!CM9b66+l*HTdPm+)M|e5yT)I32Q~2ENVJ*ZH;JF^Y907{XNHLoQ+85J~!w@3h_5d04o=~|1 zCBAvjnXMn`S#qMkPZE}9#RX`%al{`J=oFKk(aJYT&Ss`4iBrXa_pQ=3lS1IUFA|Rr zgnh;c8nkGH)|*yyoUZ?tE1XKwkF$n6`sdkf^7)(wZ52xtm86N>o&&jG_@#ue(B`xPM|8oGz94>*kl17-|d^y0`D=&hScq6gGQ%Z6|LU zG@<~h-R{xW)y7k1x7XFw!TWW~HPC^bCO_;xG#A4he?=xkLjS=~U!uR+q>vqJxCN~J z+I}|P5RTv*qRT{k2N^Kz8OX*mz$hYR!aYq-f5bN4R4=omUVP19L|)EZq?O0#B9 z<3G&oAZ`UeIqZWlujz8UNNSK#{=_c`*(&TwlIr3ZpC0sfS5Jy?;t+&wb1g4Q91rRNiEt1|L zisgH;)V()S&(TSB|1yAxZLH%BY`nnhUw_6sz~zdKCCc!ZV*Ws6`U4u|CBpv4pYIX1 z5*)5C*N#D}gj<@pdZxtw!`5aFVQ^Jj?1W z+EsBx6>WV`%wnP@Fp{XlqFkbHf%LfCgIi_|w?uPPjHAgOF+lDnAb+WEB+i_53PFmu zj!=umx@ez9mVxC&jA_RtKRfQG>Cz`A77S2SpOt7%Rt*}fG|yO+2t7CMuK$^}D#i}k zZmO9yUwK6%!LbRsULVnxUxfxso5KFES=!WCm>y&YSR@0CS|iON0v59pkQ7dVA{j*+ zmcRtD@lxXuFq@#$DKKSal#ApSJLw58m_NIJ?z;eD3Z8u*-#}EaK zyG~L>-7laE`Y}{g#FPs9YA-wT4>X>xRNtTHp8_rhvWA|eJH(!o-G~C&tvHB9$UEJI{ngD>QjBz=wl~x-j1MB z4)L_#jZSvaQkbmVbN)4{#^r&ZmfhhV%?tet3`xJ;#jI}DsS94qc&s)#2kXv5pkt;K zaY6emqzF1JWMxI(7h}mk*MQ5C8WLAol60!DPj|u0jMrLTkU7G?ud**S@bYx-vp$+r zMVXWc4H}2=yF+YML9!k~LT(|<#By?F2bS~weMi9dD@DA&k#0e&MM1YT!qoQDeNLwB zA;{KvwSzP?-K(>@_b@4vTkIX7xwj}ckrusCw!k=#;Krt6;}3q4d*)?c{>I|C2I^4p zR(o48TqHbw?4Z`c`>?P{`cT;FpJoFW1wJ3IVO#5Q`wsB>o>zsRDDATmct`aaYQbTL zJVlHeok9_?w83#Z*J(_BMs-;N;mNeq{;f3S zSy{i5hNY5s`c#)~KhQZ{0_hNmrMD2b7CLC2+x#EmLcNa8V1Q=jz@e~VV)Yq!Z|$nv$TEG3j6K4opW+mH z3~z?*H$qobb652kQ}ZHFHUVj$%JAwS-Ie=Vh&Iivx3hjMCZ1k)4dRjdhxRb17P;Gz zZCsB4J=l1S8`O|(g!8c$aOMaYeUoCJj&n#kbDxe(^GQ)E)$Rq+i-wbPKeaQvL!`Y- zcL=QOLcWBdDq_`HLow9P5BG2EMY$v;w9cR$C{ zMv)5zrmYv!uzHFAxDI>aftAp&ad>GYoPt!d;A*$s)^6E5l5ct#&O7A0p^8J1ceXa) znIq{NgKbbOSC`6E_af2bCoI(gD@(krDr^mDVw>cRz3zJ^&9kbuf6)J@Cd#zbnko5m zdyD^j^!9J7`oH!u{~wlOl7jYM(OcdI^#*5Y>BjUumq_g&tx<#_pkzQL3{!g?50d=#eCov*uIw$N*glXJe1F{FuUF_wCElS)Z2X= z8&w0?WkCX%HfL)#n-m1tiLy!jDMqH$LikJF=#lu@k5%&vN zOEmQQ^n*t^76E;JhHPzQqbY0+m8GQ9;~dJLLZ@*sqVX0ui5yz%8Hyn87vqUisY_0- zDtUu5haWdOvDBOX9Y;=s;7ul^_xLxfU(?k(HStRfk0Ab!pY(scal?Nz{Qu?etFHNA ztD=60Y>dte)hUle1IUyYIFgMxgGpvx%Odv4q;WPV?Zj<0pph+zWMfSd=SIUcB_#7^ zgNlm4(v!WIBm4?kpvZnCvp?TXW7~Azs3LT8Gh<0Ew=&W*e+4X_xQ{(e+UCESTaWwz zd1ly>%|#A|W%fgeL_3gAwxjeb?Wi3rAR3U#9Rie*)dfz7YxUK;ex+a4F>@qyQAL0^ zZncndzG56R$F&?R4SOX>&%UDdBid6 zIn=GRfcto+s-%gMB)Wx7!_Z+SS)f3IG!&s%P2eNfHI6~E*=>e`^RpvJQY?T95IOKL zeX-_BCdRE#f06_QAoDyMH;#IIBnT#PWSOtks+PCo`04X-brsea32I~@X(Bwl*Q`$c z{Al@04k=Mmd0}}ts=u%dCO;qn-;qh>Hr7bB6!NOVxy@Yi#GK2vusj7iU9757HTqN~ zNMoKeZY}o)nA*{CqTTPKnWi*JgZFZj&EjD$V;O9zqHV#tB#r5Ur$V3To8iP-bO*Gl_d%qc2$SoU`Hu-6*hWbuWzAn(83_jZ%>P{PY3XVV!q$~ALE^GC( zdIGgR(HnV8Rn*P^7b8#AzONo*U_W}{Ne!=#*qNJIRZzapu_fOkvki(|8NDg>&D=OZ zL3G)1WS*8CFh`-sb*#8*hIN7WDjw6<$D&T|B>JPi`K!*5DF(O*^A+r*Jfnt))c8|M zQKtgEytAqpy@~XZGnVYMJmZSG0U~uvP?i*?DhgDOSYtx6s%6u*vL$SW87`&xJ9cmDLrPHI@G7Pb*cizPGf|!5th41a2ijel>Xfk3i?7Bd*{|)@>|ZBi zH6gO9a2Yd&_ZeKmNQC^e&S$cl!3D2oBCX)C;Ve{0qc|4+*fwK!x{=QYtb#3QD1|Yi z%r?t<$-Mjbli1fF(C?V&w#;Gq3-**PgsGPPsXN(0fb?pIDc{s6b<9{t%6D*47A9ZHlc4rEGU<}u;tiom3^lA-&)1i=j z|I#)cctK)AH-b2*a3Wm%Gt*;#GWjNF6q0q^Evid`6G2yhMg_4TaMUK&x*D*5+KtlF#!)86A7pn~&yvD-Rh%`@(o!Wc#9t=t;(9_y*(MWS;4cPU&cJcE+h} z6fZHrjH@7{6~n40#qgL(yA-oVrt;Kcu=fV1WQ0QY`_I8lVds$PYR7KDvhsTbkC8q6 zct`{-n;z2!($SBZ?;(ZMu1sY(VY)KJ@%p)!LEBL+M{ck-$kHEx=3N+%$#msc!LKD> z?(7`Owu6Iuf-Nb|5wFxCm}U)Du@JO|nHV?%8lk(y3x-=F_d}u8>#AU~iWtSD6|VuV&YM=#_v-HDjZ4mS|L2%K2K}Mhz zVb)f#Q>%4Du>|ea6cbNYrpi<6A!rSmbeh7+xGZ{-TPG);DG9qg=>9!44ScDdh49-_ z;|KUp*RQ-So$jyV%Ss5FnJa^|LYAl%8niBhd%(W!x$Rpq@pcp6(XF^fHFRF2KQP>$ zo@`Qi&QlkFxp%0@2)7RlN4+NzCWo{?_x}5$E?kh!!UM3Vg9R+=xPLWty|S}5Gt_qg z+-v~8k*0?Bf0^Q+IZS56Ny~Q$pap&c2NUt&f7P9P+zEz*>bOO!5J8(uhIJ#%lgMNl z3;y^@Yht z_Dko1D=J@nc@`zIXz6dWsr`Kdt!m8`gGlx59A(t5ZjDVmrsjl#0wT@It~$j=uGRM! z@XJK@Q})NA_sQpEZkNduP-h{cP|l+Qqwr{g--LeHY2&||4dJFD34ZCj7@+4ZH4}La zjfr1gHXr8j#ppOa+gkiuHYf$a+VGA${f!~LtdO!~|X+>{b zY8=`^(0d9`z1f!nNzD`;4&65cNlg)@h5m5oOj&gG%mslXlc+jou#n#`d_l6}hwB+CG5k*Sr36Yrz zP2B)Pq#G?*Iwb)FJiXU@lTvTrdR&WRpV8sUz(Sx3C%f;BHSLY@I$!TqSg!%IetroG zD$gu&K<>-imH@Bh&}f!zwO-`w8Dt>MMZ>8V@{X1g?!2BS0S;GtXTW(%@{L=6uC*fB znj>TvA9Cj80~Hn`A5GSVpyqA$*6rlEa`u=Z!{-DRtCo0{jnK|3KxpDEi3&^DwWNg4 z%|~wf=EtEq^ku$fbX{@*EYr&TP@j@?OyLdVKVk*&H23K=xzmgV8p0Y|jK+@cNaPE1 zovLSR73MssgV04G7S-h7L}ID!!8|-X7U6-7?t~caWg)yk6*s=m)9us~kZ7pC6I1+@ zd&wXWPx{8Z>47wN=yJJ;BgQ&`z)H7hxm}Jq_9GiAq)9R- z7(@1=H+oqdJ(YFEq(LiJW=s}h(Yx~}5%_cQ&3xV0VUT%{sXE!% zVMqItDE@pLL%E2I2<48s8InBVbnt|shpL|$wrvbdWe!LJMr$c+e86OWy77OJ6k_2&3KMqL9=QFd2QUVwwR8X*sgj}5OpiFWK zkiv)DX__mAlH9kRszqfgqLLvBrDbP&mL;Amd=_UXSF4&!?$+*0ZswW?9oH!-BQgjS z*IQf1yzUikvx`UPXLZi2UvHaGMOee-cPA0C5fni_Q zcj2Hhbit;RZ5t^!?2;o_*D4W$VcsfIc+m?Z?b!Uv2;-s&XYSCUiczc2-b0I0g-hNj z@xi1}g6j<*=Dr7UMa-%w&YN`cBbWT>BQ~p;QyS!^#eQ>q9dy!?Nrh+?bfo*_kEe;nyR%9=3OTAD90?RT8#Bk}X#Pkr(TqBF2&!V=` z^iWLr%Yk96POnG@bEb?cv#Uk)5}bP0=~;%g>Sm{t#hoNp#yeFj7UxuD?en)EXw2%= zTS`>YY)#O023TqIXj@8o2KAM29NQM4QH=;sYP$pcqtRoxg?ZK@CWy{=P7(uI7%TOp; zP-^!0wmMVv-f2E>6tEj7ZTG#-KaZMuUUgl1|nl&p%3Dc8tZ4 zW{0iAY38oin5YwiQlKRrH8RP-h95fX$>v!l2*6R~)3vTQ7V(gjstAxGVc>U<8Jwb) zPTqZIfoIV>X`vA2EuAW0Ghj||3;hwn0w`nHnL~5Xr-xuSDNmuyhoZWBBa|hf3)-7$ z6nhe93c?Vv(WT4=mKowy$9Fu8Y)h5yEW6z&zzB7;Yf(a|ei#jb>!ayFWo?MkgWxQK z47{-ws_k4#8xv#$x229MEUK#x*X1k=2QLLnaWhYREFj!ta9&)3I+w+wuB-hQ0SFLZ zlvuP9c*O0k+Bm_8bPyfY2o>Ts&0yRSIg4c@Rv71IVHGS{L3?%!54(HvY;tru5FCHC z9_ER%i7@?-Tq&gCLBVg_3g3?9Gu6P$T^70*)YqUQTN$IHtc4g5UG7WN_J&c!4-lZ& z0a=#~p%2D>Wvx?z(9bP0Z<&FgpEnI^CYsg{+)}t}Teb>kj&)7NNmPz4Zv@MJA2cA4 zE{uQ3IbdMxWrxK|%90Rdmx)yBJ3FI$YLuF4DF~35POQtBilKK{44PuvYIHjt?~mW& zzNwc$LazTnX6dO-hE|>Wu0KO)5xDdvCq>WTfkeI85j!LDvSNHy0&TTnCpr_Y@_=eYt;}dhqY5=4^QRl&pzt9Bed!EmviR=h>B6ynC7MGc`x^9c*)$$|imA)E z9KmcfaDlPY6j0i|;UW8=8oO5$aRyZaYTM*qBd?3;u=u(KdjqYJ_fLd`tRoym(-gX) zqoT2Ua$jR%Ibg0>jte$VWiyOhLaYcnGe^pQ(V0O%I}YnENL$+J%d>ulP(v~JZtnH_wYk$}A_OsQn5BbzOkG2(!baa2N({4d%BrLdzn_qpUhmGmod2kf3s)xrh|=VU=smdZ ze#hs3hAI5A(;4e45x>FbZjXU=hACbM{;p^HFvP31DFz6_lHCVuZC63Xv9`wzN@Y6rcuoPF<~3V<@&m2~m3D5&4GW7GA+XXs{sPo!wDK z85d-&4Og)(j6Q8x3f?Ooxm7VJf?Nw>3_s3fV9y_1xSDfCy31yBhkr2LI_&)xUpcLxXfuNl6z9z^w)MF}E8U)#3YWS4&8 z{-CVR?>0{F?ccm>oP#mMTY-&w90y~vwccFmV3Wd60@~aufc|xzwLI_AA^-goYhcMf z>+D@$bjnFLRX|X?6oMyaW_}(z!Ys&@5~HmlWUY|}!wJnBP8YPsWvf1%(iPjQZ2#s7 zd=-ANqy%pCwL5&H8Tzs{Ux(<1et1ny> z?C%$W*FgAI%!nl0a{QuH&7L*cr$DOVP-67{8fQkKPfPD$L+Lv zSnj#tSMG<%-tcmKzH8dSPFO)VC^+Dw0|si;bY^#=`Ilum3dEF5!JrA9J z^7-aQuXu7vwaQBlnT>)~G|scmodeOzMFBpiJ_`6WePZh+=vMX276uFz4Vd%}>sndc z95j(>Uq_*mC-r*$6iUb)5mCYRy8>n-Y?K==}9iFFRN zB_u(i5p)JpS@Is*ArpnM&nOOwsI6t6IAmTNaVm+)*gWI?2fN{+=&1n$oGYcUGS!0y znn-1azfTgI zyHQk7RQGW=l@WF&jO?B1KXJa9;4BdKcfcpq35}=O+x=GE;TGw}Ub3M+AbPW8_LG;zZ%{IenPEAQ0yCE`_ z5medk+}GQkcA+x*kGZgwAC&01r6-zspCxwld`4~iEZGot%8<4p%sS7d>FR_YB` z1Ifjyuvj`fc|U|FGJ>_SBP*e_IMD*V%9fftjgs&{b6*4#VT3Vun6n`CvL$#d*2ygL z)7eoDSMZ1NGifW#;&EW?%%%0BG5R6&cx8T(iz?c$ah{_eCRo%Dp%dN0c9w$xeo))f z!{R2?4ug`a98BH;1&H}cNC!iP7dTNKFKcpxcOl6#wP-SCOy% z!JYwOsHXEGr4S3cKrNjJ=%MF4T z@!bVaWe=0&6`nIQ;)FZc{l;u(ho}|4c%t0S8wEmM$g~?uCNTxxtk^R4o;IIHXg4Nb zZhIyY?230y#03^WP!{XWxKemhpfBjbwIDOpx8d|`8Pt~dI`s(SzLBSax8yVhRmu9{ zw$*00x8`h$)GaBWP=7&dA{3Isa5b890UcZ}9{lKpxjTOUjiBd@0mQR5q$sBg0u@Iy zwll8RkI|Pv!)|-}!4Q;*3w)M>CtQ|YfuY*dE7B89}m%)-8C#3~yUl6@M z@$xCS^_0V!62E%u6hMI}Baijc^H8CqqH=??%n$8DrN(@_lxx_H?j+3I+s>0uS4W-> zq0;-tBt+ZUCJDUZPCC#K`72}xS)J822;Tq5LaYD!CkRo6su~3oN zg&ag$fC3ZxSR5uvsAWN7eFh2^)f87O^;9TTDscs|OpfUC5ghp1K49VjDrt>4fKO=L zLxxhlumLD^ZNtMYZExK9PV1gvZsMjXa&<%d^2M4I|F-IW|5xsB0rGy*D60s$dYsg6 zMdyH$$qnp@ADG-=TiGN!GTMc$NnfrNngX>@GClAFT;EKG&5U1Bb*)IV83-ppR>OmP z;mE%>wS^m>hiH7_YYVSpTmR5U_95QXcNL(22X&|AmEtABFNSh^r+yF3YBOQc4!O80 zW_5fFeqSWTBALo%V#({BIC-%Lq^vp1z-V;gLfX5Rua>+TgW*Re+49!T|9sLVQu&ivPtDwn<# zB=%%^7~>Vd1WyRru7m;?SybRpuTdTkp!CqN?qy2_^y(`WSe9uYa9qE|o zcGg`Ff;qg;-$@F&9QY~YAiHAU+kZCb9ucTo{Gb6k#xmH@V2*O=2$V9hv3N!FG!${7 zTp-rnDN>xcgi;~=_Mxb*sFFSwD6?;CdR1Cbi8F3{DehvaW-t1+1l`nx@J2Uuss#I} z7YEQopO?lmS-vrY<18fFZQj;RUYHV1%R8M@0Tkd>SU5a}8CH-r{t1(N7NT#$sq)^w zmVCLx`_@z>k8uq?b|oJ{kgpSC_o3O$%4V2RH#rTN1lnS2uTuJCihJod=< zbK*bD&;BL?vnWrN{SD(*)sBR6Em-F63?LK}2oSl&aN^HYHdZan2q(BF z)D7uS5-tMDl2IECM|7gx%2> zc};Ho`i;kR%Dy)GUpF~6W1Ki*Wd%6#FMi5xBe)PX;SaussO4z3-v?U!u2?q%8AwgJaANO0!?)r6)*$^idCj}7^=gi;C5G{41QB@Q*c8MR zn@7|~dhs0<3%J0Tf=dI8%-XKKYj#sRI^D}q0b6V;M(o(HwO9@8wBzAG+cAYdGz_#F+444xshfBlAac=NZ;*fOTY9TtZ05z^pR5AEUigsEZVK|3P%EN69l9T#rt ztMj^w%zcjN9ADJ>WP_UYuZX&jZR@ji&u>=*IXGQau?w2zE-No+$nTgu_GgZsa&$M# zZYvI)dh>Bd=#L)dh+N*aEL{^5`qD^U_KpbEKUE%6$K7WS@R1G!nIcLmnv5J+Ack3a z2%04+f%{()h=i%kj`tsqCkKKoh%KE`ZGs_5p$zYHg~mcPi@d*l{hE-c6mFY*IgBX* zL6~^BD26Gh26+p)EPJ2IL;Sue$6HLwX#VB^s1h4Q+Hww|5(zlpA&M+;`=Svm=S+;v zJkHERRBWx#%q|GpK%F+Rc$V1Q(oO+`kKp_?Haa3}B9gaq1r)nI#4!25hPe^VDlLJ6 z5!=XtON&dC5`5o5js^}ccFq*%Q{E2ZcqcfHG;3~hzIV1Smr2JnUrzA}qvJS0pHByD zCj6^D|3`QKV-Mkn7l`7C+;{KiDa87OI_;q(s#HJaMS4T(P0Ely98^+ZR5*wy_!G56 z3+J?z-u?HtV2|%ah$ea4I0FGlLpsR$NLzoiQt?zYqY;)WuKzk zX&zj^7gwX#;?y|AsCmpgmqu;LL}sQV%xExYp;~&@;1uwbc*ZH@^yP4QVY8iniz)@m z`NT(X?G-$aA(h8Yb5{k|ODM1t4fD*k+EhMk&aPsfdgTiZ`crm;aE@iffH$0xl)xzk zP;cf1mo~EIT*L1pFr>c)6bMypnY#=C1chd$F z%xSI__^fdrclZD!Ywh;nrQKS)Gv4n`Ga?-lrHjRFhZVaU8$}1Fr&DC&0+5EHg+pD* z&pKO@6Taone5>3KFT+$B7Il<7`8grSj`|R;58(C6d48Z%;pV6 zj;G<~o22D(mZ@K0+17Z31aLV+Ib~<-!z5SSzQzTB0}{rh&2duz%ly zaG}^#dJ9k$#eoF^;`w!0|1(z1zu5!@L z@tL*vL%QefR>d1{NE>i|3C`dpl0@?KUi{TkiN6mGNRUDey67%i8-Y4@?C?4BK3S) zfr7HErec}l`_~GWBpfXk`;cTxqhQ@?lDsP1%O4g~b66sRNmD#`1VWS0+t5BO78E2& zICkZ`iPxc*m11BQxRt7dE1Ik0(P7<}s}!ezaiQ@+*Mlw==xGFmqi$4i>jy2&9mUsA z*j>?_P%uwoz{pMh_#KrelvNTR1Opo6mb0SRdK0M!Onk`Fp z=ys4!Z0vaFCTK~5b`EdIQS#2A*Qxqp3-@B7aA|=0WBE1wz(P~(nkuXl$tH%v&|#9R zeLm0olbua(?JgZv2G?R6yz3gVQMwP#Y?)mq-k6@gOK|{k8!R#T#dqf~3JgcyYV_!1 zp9v$!CMgIg^wGUhsG`m7QN0#1VZJ^W5m6TdZ-x>ULth(W{8-URkIild7h~&lW-x6# zkamVW=Fm$^>gUSsTS%jcc8$w;GJ85Mm6ERkFl=0h8YO#a*X7vZdhL(NZ^$yXf-l)ch{DbY`+M4q6{fN>WVq;uQz|Q)ZP2YT2wh+vZ+$wOqNyK`2r(RlH>uebaK2avbVcg z{@;W^5h;qUc)ExRI?u}9`&={vL4h#9%kfVg8oSDKpXrtx)=Dkv95RS`c6_Ya%CPQC zTS5MSS`B|Ys|SBOr^kwpi#7i^XAT5X7Z2tT*1m^K5{>uKVM+tlmjz}bI(8LGIh*ms zsMRF~)Z zhf64Z9SiFjJH1?Ww#3?_{~Ehqr&!d1@{PteLg{| z77qv)uM`QvK+3m{7!R~TPcnJ&7Vd@$JSpSW?&Q|)()t24_zF+GMe1DJe9u=JL((pz z4@A;xoiw;3?LGCEciG5$Z{N|`rA>OUUZZTmgJoTfSjMXtou~^{@2Gdt3#}aVPkp&$ z;<#mYqWv~IR4PWq6R@TK>G(xHnxscc2G>Kz zna3IzOUIMP6YyJPT55w=uM}j6{e%$j8MAVCg2K`y>GEQHGW+Q1C~P&o&OS8KcHC@N z=WVu!LBgQ8k675M3KmokUnj4A2`EwxIHITBFM{dT(;41?F>3Zo@~au76RvQJs*KoS z&L@-VLeWtdWPLNQgrr$_l(4LdjNv_DW?{dFzQj%)S2oXPWW_8#V2>5y%Hx-?Of->d(WT$~az&0U;asF!k=o??sn0dY zP~Sai?n7|WSX9ty2<<9(n`Ys=AX@RNRjzxYcMjsFZ?*klo(9`Xy0pz%+dO3^(+0== zbA1P2Ogj6>A;Xc#xtnp7B~iZ?OK=h>aDmEqi5QqA&V7UYaQwbvoMw%fid2k?v=$&W zU9LC1N7!8#Q-WfmkA|V1){F$W1nSN@5^O7TnxTnpys|30Y$U>gDEnU0u7`$EzCUgxKF=SKK zc(M!e{m6AkXWHEu3NF(2SA@7<23J^(Jg^;%h5KGp(c)gN$N7PNs6sUOs-M(%hY-0? z|B;LE-P5z_yS}s1J{j;76a!AP{;PNwe>?_)&boGne>lMWCEi7uGGMK$fW+GXaJzP@ zLeKG9htxxEMuTA+D1<>_B7;wzX8q{haH4_P(6W0v8!dhg{dEgbRwR;)&j-;kT{BT* zGF5alYiw*J#lFCK_w@1W)i+2V*HX%u9(Z`}>My23@3YcyD46nzA%%NuA6 z$lONl=$>A5cNf{XGkwN zKJmz+b(iE7?Za|mYx@aj!F+AgUP^!_!U^+IR_LR7^Wd6_?3V!V5M8Vknv-+Y*0=VB z3RDkWb~q(Xg>VWlaH=;l$s&6kowW8sh+In-9=`2&@$jt{s5oin8d<4-abf1&S1-yY z4Xll-Q5$CpVd1vYSL)4;BBv`+o2Uw73krO-6KUK|T~D`hx1+))!2)*!D_zF}$3nUF z@+Bco^6H5c!eU*o;#dsv6N7QlCIKiGMYk#s&zjCk;|@N&6P?8zHiT>2<9Z~6OW+dy z1;en?LH?maVakQZ=w<717oPTVD5{odQy#~CajBt5Rs?}0C1?oiNK3OWSt#y7$R%ayCbDQ7oAH<-&`Wp2>)fn@T+)hdW? zvE+)d2_$+7ALBDazH-i|WSMsT%KI8p;uxa*y6SzABt(4(r{>`#y^}+@uNBzb65Cdz zz%0=Yndh4^T4e5FymIOP2e;OLU$IhxNx)$Py!MR08zX)l`2XVJ z^~^~xQbAU_TL8%u;DbF~QB3)XgcU}tLY7)W0SyEOdbQ!8*+P<|dL`kJ9q|#!JE2iF z2P|F)Gcm)p=B!P3ckkv1x081a-vK`zC7nzWwj4fZ4YttY{*0j83 z`PT;>OuT#X3hZf2Y|#0OO*KdOdF<`w8GXTMqD!jidZDjP_B-7vFClC@%wCpeyiVBR z-jHXmyT>GNns9^GS}Ruz7(N+Gs|YythV2@4+Vsb`i=eGpP)ZXpdFz-;FN8{;cCt`v zc+QT8%U1bDX*pG@Uj@NNt;c*Ds=wF$3*_JHS9k(r_YmL_=>d2n_*Y@vV3A``LM;>6=Nn|z zre+N07A%UrbNF+fy2fh#6N|1jjqmfH-t*^9**oh)QB;1kEqHS}+ypo@-}EWd{rd6h z%$flx&-P89`bb8uk&YOaJsvhT3Wg!wx(1MRS$J~<4L!=WM+XbG8e#Rw9dqM9!@ z+#_6QHns5>W898fQL8nHugDl&2EBr0Q&x_YDt@cktT5=HQP5iCd`p4gHB$_A!2NZi zfd&6%=r+PKcF zcD>}A2!}ZrljP{g7lSURAIQNm87b5}hmrWXJFAsVr&+soJYUbIW<3f`8Rn&64AN|n zSdEEN^c|s2!F}}qI+8?SVwkqY15P7FqL;E!ycf$J%{gv!1HO@T*!_;91hNgu4&Yv_ zLVv=T^B%)U-s|Imj%(pjRp^!<7P~u*P@4{oI(<@|8!tD9aMICh#2eS4$eGG3v%|!D z3A9hb5HtqpqehMMa#N!Ts_sj&kZ`-;{^vSa$2KvUzQTu(^Rn+6Ub!urJ5;1XyfGF+ zPk&ug5Jz{R?Xt?FQ>0Rd;JiS)`RxM2aDHoU{Tt$KM~`fJ4=u@MHp~=H1h{{0>(l^Z z)`#oM8@Fg94%5>@ozPzIKn4u?Z9^Kdq zb>z6+;*Il{_Z$%8;%)VaMOgBcyqA`}UcP78_o$yfdftM9!cK-_c98twa zHqXs$;lCQr75r$Jq!!*D1TBMN$&{KKiwJy76aO*8aAD0)##01^2jiQZ=S6PyL9z`dPCX(PcIvRFR%Q%oq&J*9@-?yiy6KV#!b`ri50d zRQ+HHJA+XuO_7QOd(_ieE+CfY<*sY!`#?Q6B zy5398or>DtM&>Pt;fqQzX%#y7TO~D@!Q8N`jsznSaHVV@QII_GY`mUV{igy`NP(A}J%X}?5&&wsZWPQiBz zc?)>svRp9m2Q!__B)myK^VmyYTJ!dL1hE0?7sFX%XPzI+HQT~=qMN2?g-TJ)yv&^o zP-?RkV&wTaPG0K7dqAKQ@lbwGb9HunYmN}@dk%i*Y6CgtG26<8lS=_zY90qI7DfB}ire6El{#mc z;nEwoLQ&~Dc`v!lIOL$!8Cqc^q1h(sj5ncZeba?%Dy69??%`Jp?ZZZ>TN*R4Ep}sI zw{?js2HG>`K26%gY%2}$aMg~J`MfG&2;w$5vc%2GLM?tmm92FD7>Lt&#@luqnUb7n zMTH2f?x*aH%6_dW3+wKB{N5x-bY8Q7_w;nlC+dFhl!&BN&Ff1*S?}lyRicHzJ65=f zO#y?AA+n$PMh7kEH#NpfC>Lnwc{{Z)Vlk`VfVXgIAuJw^YU76nsxsw4)XG69SOl3M zXsToc7Sjz)_Km2o@OS4l8Pk|X#8Bcodlqp{eX(rt5%t!Csf6D|iO(IUR*jxn8u2KO zQ2ElC42(){N+?>x3X&7oo+mgooiaS zIvzb95Qu_Akw-&VCsEKR{6ZwE1sQ^Dq&q8pmb6%CggTRbctH9@U2Nq8LLNW}pd=Wl z)2ye3h=#^9CL^`Tj0Z|w$>T;#V)NRoh|No=l@&1z-e+UkRuibQ&9wG2&Ky}hRs@pk z&{u^6Votln-4}O_cY$AM;?jnlE9nfz_he1h*m+5^E44Gg@Gffy)%TbyGEpeMe`{2) z5*7nD8Bstj#>{{T1EU_vd5^`35WIP5gh(GPDeFoGC)=FJWY{fZomyNDEx}y7*y@Q+ zE!*X`kfss8HWb@hx{mGnzB$zNE*{{roGJ) z74vfpFx-*xmyL|>aP{5|H_RRB2nK&RUyU)Q5Nyxk0h)N4isUHfG~i4EXs`76b>R{p zaTE$B^0yjYa0Dz4T!#L-BNMU4i_Hbr=KTo*#^mn;q#H-@)7~#Sw!WzJVyR2QRWHPVe)!r_j!+mZ)-gCwne;e2sekE2s#u zBB@|AlL)>RmIfI%!jyQ9yJ=36Y=kjt3Ss$!7>SBfYIXZ3iz10mkjP@voHl-|)^tIh z#IY2OH0SyP1y$O`Gex+}Lv)?dR?e$O)x$1IK~cET zQ>(H{FhP9X=x~9~8;=t1n2V;CyWI65+}B__iGq-W+!Er~oYCPvy%Po`*xl&OqhjBD zAY4Ky{Ib^XLF8{~54CQ6@9!S7KA#DyA;cCC4>(OU)A_lDLI*%?VKI zVF7!a^&(NWCGBf}7T177CBQTaEqJ;4=I>8sWt6@0_tP^XfDa+y^Fs#!aMb<(TLYk) zx#~9>06Tw+{0|I*1`1Fvhk^oP1X%b0y#E*V9xyumxR8KO1iyck6;%?Xmy{C&9Mu1N zvW7l2DgnShC<8udfX|;-p6~a!#s5ntD<~%^CaS3PLRRdr2;|R*0khqY3km3(U>e}N zwVm0c5a{ypIj35H*oP5cau-UI%12Jj*Mk^K9u z))ybJ{`#KRAIyIO{HY7|XQcJ#IqF>voJ9l7^EQBze{cRjuUcPVz+e9f@cF6^u)cF~ z6?Akk0mQyF)&CjT`8ng>v6_7`fMyBsA^DRIaIf`s2IS#4jFNwr;g6Th=XhX6ZYx@V zyea@v)Bg=m7ho&?4W782u7QQ2G9diCgteuijJ377qs{N3@iw)WdI2E!fL{82L-^0D z))&xce+LbS`D@{54>(sQW@=$5sIPBmZ!fEBrEC1B(!%q+kHG7QeUG4h2e9Y;J?{hn zQPbb#UG)!X4uGk{$kf;o5I!3aO8)nGSMbC)-2qeyHX!eee`XwTul2o0`YrVH_LKmK zMOgf|jOV*DHmd+K4g{#3?<2;aSFJBS#&6MOtd0L`EsWV6g`ordOsoK9{(da#&#TtA z6CeWen_Bpr?A`B+&$(K^f(v-Wjsc?p(Vu{Td#x`v;OB2J0fzz|bS*4?kG9e&6WRl) z%y)o+>F@1i2j~~SK@+mJcK9y4VI!++Y6Y;l{uJAI-UTFP8_1>rZA1zv>UYV6Kd)L} zU(Vk`|L6juE{6J!{}(;|Icfk-UP(0oRS1Ae^Cu+WUhA7G{9DvN9*Q5>-!uLDig>QM z`zLg*ZvsF><~J4bqgwyl@bg^b@F$)FU_k#3-rt)3zbPI*uZ`#Wc|TdaRDa9z&m+!r z*_@wnvv2-y^87IX|8@fXYyQ4(ZatU1`3Y$J_P>kZJV*JS>iZ-4{rWB&^T+jl9<$W_ zTPeSXuz8;Nxrof4$!mSne@*(7j@&*7g7gZzZ2H25WNe}Vn+a>?{-Z~R_w z&m}m1qM{o93)FuQ46!nEyV!!gHSIhx~u?BuD(h^XuU8ua5jb=X`!t`zNPZ^#A7k{c!c% zr}ii2dCvdF{Edh0^GrW?VEjq2llLzO{yIwiz68(R$9@tF6#hc+=PdDW48PAy^4#6y zCy{UIFGRm|*MEB4o^PT5L=LX_1^L&`^au3sH`JdO;`!F)Pb#&ybLsOPyPvR& zHU9+rW5D=_{k!J{cy8DK$wbij3)A!WhriU_|0vLNTk}tv^QK>D{sQ}>K!4o+VeETu zbo_}g(fTj&|GNqDd3`;%qx>XV1sDeYcrynq2!C%?c_j@FcnkclF2e+b1PDE++xh+1 F{{tUq7iIte literal 0 HcmV?d00001 diff --git a/samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore/java/retrofit2-play24/gradlew b/samples/client/petstore/java/retrofit2-play24/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore/java/retrofit2-play24/gradlew.bat b/samples/client/petstore/java/retrofit2-play24/gradlew.bat new file mode 100644 index 00000000000..5f192121eb4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/retrofit2-play24/pom.xml b/samples/client/petstore/java/retrofit2-play24/pom.xml new file mode 100644 index 00000000000..a6cb9f52121 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/pom.xml @@ -0,0 +1,190 @@ + + 4.0.0 + io.swagger + swagger-java-client + jar + swagger-java-client + 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 + 1.10 + + + 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-javadoc-plugin + 2.10.4 + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + com.squareup.retrofit2 + converter-gson + ${retrofit-version} + + + com.squareup.retrofit2 + retrofit + ${retrofit-version} + + + com.squareup.retrofit2 + converter-scalars + ${retrofit-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + + joda-time + joda-time + ${jodatime-version} + + + + + com.squareup.retrofit2 + converter-jackson + ${retrofit-version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + ${jackson-version} + + + com.typesafe.play + play-java-ws_2.10 + 2.4.6 + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.7 + ${java.version} + ${java.version} + 1.5.9 + 2.1.0 + 2.7.5 + 2.9.4 + 1.0.1 + 4.12 + + diff --git a/samples/client/petstore/java/retrofit2-play24/settings.gradle b/samples/client/petstore/java/retrofit2-play24/settings.gradle new file mode 100644 index 00000000000..55640f75122 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-java-client" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/AndroidManifest.xml b/samples/client/petstore/java/retrofit2-play24/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..465dcb520c4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 00000000000..4abefe6b890 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,136 @@ +package io.swagger.client; + +import java.io.IOException; +import java.lang.annotation.Annotation; +import java.lang.reflect.Type; +import java.util.*; + +import retrofit2.Retrofit; +import retrofit2.converter.scalars.ScalarsConverterFactory; +import retrofit2.converter.jackson.JacksonConverterFactory; + +import play.libs.Json; +import play.libs.ws.WSClient; + +import io.swagger.client.Play24CallAdapterFactory; +import io.swagger.client.Play24CallFactory; + +import okhttp3.Interceptor; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.Authentication; + +/** + * API client + */ +public class ApiClient { + + /** Underlying HTTP-client */ + private WSClient wsClient; + + /** Supported auths */ + private Map authentications; + + /** API base path */ + private String basePath = "http://petstore.swagger.io/v2"; + + public ApiClient(WSClient wsClient) { + this(); + this.wsClient = wsClient; + } + + public ApiClient() { + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap<>(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // authentications.put("http_basic_test", new HttpBasicAuth()); + // authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + } + + /** + * Creates a retrofit2 client for given API interface + */ + public S createService(Class serviceClass) { + if(!basePath.endsWith("/")) { + basePath = basePath + "/"; + } + + Map extraHeaders = new HashMap<>(); + List extraQueryParams = new ArrayList<>(); + + for (String authName : authentications.keySet()) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + + auth.applyToParams(extraQueryParams, extraHeaders); + } + + return new Retrofit.Builder() + .baseUrl(basePath) + .addConverterFactory(ScalarsConverterFactory.create()) + .addConverterFactory(JacksonConverterFactory.create(Json.mapper())) + .callFactory(new Play24CallFactory(wsClient, extraHeaders, extraQueryParams)) + .addCallAdapterFactory(new Play24CallAdapterFactory()) + .build() + .create(serviceClass); + } + + /** + * Helper method to set API base path + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + + throw new RuntimeException("No API key authentication configured!"); + } + + +} + + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 00000000000..e96d1561a7c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/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-play24/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 00000000000..bde870aaa4f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,52 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallAdapterFactory.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallAdapterFactory.java new file mode 100644 index 00000000000..cb930cbbff7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallAdapterFactory.java @@ -0,0 +1,90 @@ +package io.swagger.client; + +import play.libs.F; +import retrofit2.*; + +import java.lang.annotation.Annotation; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.WildcardType; + +/** + * Creates {@link CallAdapter} instances that convert {@link Call} into {@link play.libs.F.Promise} + */ +public class Play24CallAdapterFactory extends CallAdapter.Factory { + + @Override + public CallAdapter get(Type returnType, Annotation[] annotations, Retrofit retrofit) { + if (!(returnType instanceof ParameterizedType)) { + return null; + } + + ParameterizedType type = (ParameterizedType) returnType; + if (type.getRawType() != F.Promise.class) { + return null; + } + + return createAdapter((ParameterizedType) returnType); + } + + private Type getTypeParam(ParameterizedType type) { + Type[] types = type.getActualTypeArguments(); + if (types.length != 1) { + throw new IllegalStateException("Must be exactly one type parameter"); + } + + Type paramType = types[0]; + if (paramType instanceof WildcardType) { + return ((WildcardType) paramType).getUpperBounds()[0]; + } + + return paramType; + } + + private CallAdapter> createAdapter(ParameterizedType returnType) { + Type parameterType = getTypeParam(returnType); + return new ValueAdapter(parameterType); + } + + /** + * Adpater that coverts values returned by API interface into Play promises + */ + static final class ValueAdapter implements CallAdapter> { + + private final Type responseType; + + ValueAdapter(Type responseType) { + this.responseType = responseType; + } + + @Override + public Type responseType() { + return responseType; + } + + @Override + public F.Promise adapt(final Call call) { + final F.RedeemablePromise promise = F.RedeemablePromise.empty(); + + call.enqueue(new Callback() { + + @Override + public void onResponse(Call call, Response response) { + if (response.isSuccessful()) { + promise.success(response.body()); + } else { + promise.failure(new Exception(response.errorBody().toString())); + } + } + + @Override + public void onFailure(Call call, Throwable t) { + promise.failure(t); + } + + }); + + return promise; + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallFactory.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallFactory.java new file mode 100644 index 00000000000..f2421d80678 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Play24CallFactory.java @@ -0,0 +1,210 @@ +package io.swagger.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSource; +import play.libs.F; +import play.libs.ws.WSClient; +import play.libs.ws.WSRequest; +import play.libs.ws.WSResponse; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Creates {@link Call} instances that invoke underlying {@link WSClient} + */ +public class Play24CallFactory implements okhttp3.Call.Factory { + + /** PlayWS http client */ + private final WSClient wsClient; + + /** Extra headers to add to request */ + private Map extraHeaders = new HashMap<>(); + + /** Extra query parameters to add to request */ + private List extraQueryParams = new ArrayList<>(); + + public Play24CallFactory(WSClient wsClient) { + this.wsClient = wsClient; + } + + public Play24CallFactory(WSClient wsClient, Map extraHeaders, + List extraQueryParams) { + this.wsClient = wsClient; + + this.extraHeaders.putAll(extraHeaders); + this.extraQueryParams.addAll(extraQueryParams); + } + + @Override + public Call newCall(Request request) { + // add extra headers + Request.Builder rb = request.newBuilder(); + for (Map.Entry header : this.extraHeaders.entrySet()) { + rb.addHeader(header.getKey(), header.getValue()); + } + + // add extra query params + if (!this.extraQueryParams.isEmpty()) { + String newQuery = request.url().uri().getQuery(); + for (Pair queryParam : this.extraQueryParams) { + String param = String.format("%s=%s", queryParam.getName(), queryParam.getValue()); + if (newQuery == null) { + newQuery = param; + } else { + newQuery += "&" + param; + } + } + + URI newUri; + try { + newUri = new URI(request.url().uri().getScheme(), request.url().uri().getAuthority(), + request.url().uri().getPath(), newQuery, request.url().uri().getFragment()); + rb.url(newUri.toURL()); + } catch (MalformedURLException | URISyntaxException e) { + throw new RuntimeException("Error while updating an url", e); + } + } + + return new PlayWSCall(wsClient, rb.build()); + } + + /** + * Call implementation that delegates to Play WS Client + */ + static class PlayWSCall implements Call { + + private final WSClient wsClient; + private WSRequest wsRequest; + + private final Request request; + + public PlayWSCall(WSClient wsClient, Request request) { + this.wsClient = wsClient; + this.request = request; + } + + @Override + public Request request() { + return request; + } + + @Override + public void enqueue(final okhttp3.Callback responseCallback) { + final Call call = this; + final F.Promise promise = executeAsync(); + + promise.onRedeem(new F.Callback() { + + @Override + public void invoke(WSResponse wsResponse) throws Throwable { + responseCallback.onResponse(call, PlayWSCall.this.toWSResponse(wsResponse)); + } + + }); + + promise.onFailure(new F.Callback() { + + @Override + public void invoke(Throwable throwable) throws Throwable { + if (throwable instanceof IOException) { + responseCallback.onFailure(call, (IOException) throwable); + } else { + responseCallback.onFailure(call, new IOException(throwable)); + } + } + + }); + + } + + F.Promise executeAsync() { + try { + wsRequest = wsClient.url(request.url().uri().toString()); + addHeaders(wsRequest); + if (request.body() != null) { + addBody(wsRequest); + } + + return wsRequest.execute(request.method()); + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } + + private void addHeaders(WSRequest wsRequest) { + for(Map.Entry> entry : request.headers().toMultimap().entrySet()) { + List values = entry.getValue(); + for (String value : values) { + wsRequest.setHeader(entry.getKey(), value); + } + } + } + + private void addBody(WSRequest wsRequest) throws IOException { + Buffer buffer = new Buffer(); + request.body().writeTo(buffer); + wsRequest.setBody(buffer.inputStream()); + wsRequest.setContentType(request.body().contentType().toString()); + } + + private Response toWSResponse(final WSResponse r) { + final Response.Builder builder = new Response.Builder(); + builder.request(request) + .code(r.getStatus()) + .body(new ResponseBody() { + + @Override + public MediaType contentType() { + return MediaType.parse(r.getHeader("Content-Type")); + } + + @Override + public long contentLength() { + return r.getBody().getBytes().length; + } + + @Override + public BufferedSource source() { + return new Buffer().write(r.getBody().getBytes()); + } + }); + + for (Map.Entry> entry : r.getAllHeaders().entrySet()) { + for (String value : entry.getValue()) { + builder.addHeader(entry.getKey(), value); + } + } + + builder.protocol(Protocol.HTTP_1_1); + return builder.build(); + } + + @Override + public Response execute() throws IOException { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public void cancel() { + throw new UnsupportedOperationException("Not supported"); + } + + @Override + public boolean isExecuted() { + return false; + } + + @Override + public boolean isCanceled() { + return false; + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/RFC3339DateFormat.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..e8df24310aa --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/RFC3339DateFormat.java @@ -0,0 +1,32 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +package io.swagger.client; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 00000000000..a52cbe680ac --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,55 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

    + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java new file mode 100644 index 00000000000..26c1576fa07 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java @@ -0,0 +1,86 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import play.libs.F; +import retrofit2.Response; + +public interface FakeApi { + /** + * To test \"client\" model + * + * @param body client model (required) + * @return Call<Client> + */ + + @Headers({ + "Content-Type:application/json" + }) + @PATCH("fake") + F.Promise> testClientModel( + @retrofit2.http.Body Client body + ); + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return Call<Void> + */ + + @retrofit2.http.FormUrlEncoded + @POST("fake") + F.Promise> testEndpointParameters( + @retrofit2.http.Field("number") BigDecimal number, @retrofit2.http.Field("double") Double _double, @retrofit2.http.Field("pattern_without_delimiter") String patternWithoutDelimiter, @retrofit2.http.Field("byte") byte[] _byte, @retrofit2.http.Field("integer") Integer integer, @retrofit2.http.Field("int32") Integer int32, @retrofit2.http.Field("int64") Long int64, @retrofit2.http.Field("float") Float _float, @retrofit2.http.Field("string") String string, @retrofit2.http.Field("binary") byte[] binary, @retrofit2.http.Field("date") LocalDate date, @retrofit2.http.Field("dateTime") DateTime dateTime, @retrofit2.http.Field("password") String password, @retrofit2.http.Field("callback") String paramCallback + ); + + /** + * To test enum parameters + * + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return Call<Void> + */ + + @retrofit2.http.FormUrlEncoded + @GET("fake") + F.Promise> testEnumParameters( + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 00000000000..8ae3082d15e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,133 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import play.libs.F; +import retrofit2.Response; + +public interface PetApi { + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return Call<Void> + */ + + @Headers({ + "Content-Type:application/json" + }) + @POST("pet") + F.Promise> addPet( + @retrofit2.http.Body Pet body + ); + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return Call<Void> + */ + + @DELETE("pet/{petId}") + F.Promise> deletePet( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Header("api_key") String apiKey + ); + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return Call<List> + */ + + @GET("pet/findByStatus") + F.Promise>> findPetsByStatus( + @retrofit2.http.Query("status") CSVParams status + ); + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return Call<List> + */ + + @GET("pet/findByTags") + F.Promise>> findPetsByTags( + @retrofit2.http.Query("tags") CSVParams tags + ); + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Call<Pet> + */ + + @GET("pet/{petId}") + F.Promise> getPetById( + @retrofit2.http.Path("petId") Long petId + ); + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return Call<Void> + */ + + @Headers({ + "Content-Type:application/json" + }) + @PUT("pet") + F.Promise> updatePet( + @retrofit2.http.Body Pet body + ); + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return Call<Void> + */ + + @retrofit2.http.FormUrlEncoded + @POST("pet/{petId}") + F.Promise> updatePetWithForm( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Field("name") String name, @retrofit2.http.Field("status") String status + ); + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return Call<ModelApiResponse> + */ + + @retrofit2.http.Multipart + @POST("pet/{petId}/uploadImage") + F.Promise> uploadFile( + @retrofit2.http.Path("petId") Long petId, @retrofit2.http.Part("additionalMetadata") String additionalMetadata, @retrofit2.http.Part("file\"; filename=\"file") RequestBody file + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 00000000000..84b3f99f2c9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,68 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; + +import io.swagger.client.model.Order; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import play.libs.F; +import retrofit2.Response; + +public interface StoreApi { + /** + * 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 (required) + * @return Call<Void> + */ + + @DELETE("store/order/{orderId}") + F.Promise> deleteOrder( + @retrofit2.http.Path("orderId") String orderId + ); + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Call<Map> + */ + + @GET("store/inventory") + F.Promise>> getInventory(); + + + /** + * 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 (required) + * @return Call<Order> + */ + + @GET("store/order/{orderId}") + F.Promise> getOrderById( + @retrofit2.http.Path("orderId") Long orderId + ); + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Call<Order> + */ + + @POST("store/order") + F.Promise> placeOrder( + @retrofit2.http.Body Order body + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 00000000000..7034b3ab5b9 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,118 @@ +package io.swagger.client.api; + +import io.swagger.client.CollectionFormats.*; + + +import retrofit2.Call; +import retrofit2.http.*; + +import okhttp3.RequestBody; + +import io.swagger.client.model.User; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import play.libs.F; +import retrofit2.Response; + +public interface UserApi { + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return Call<Void> + */ + + @POST("user") + F.Promise> createUser( + @retrofit2.http.Body User body + ); + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return Call<Void> + */ + + @POST("user/createWithArray") + F.Promise> createUsersWithArrayInput( + @retrofit2.http.Body List body + ); + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return Call<Void> + */ + + @POST("user/createWithList") + F.Promise> createUsersWithListInput( + @retrofit2.http.Body List body + ); + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return Call<Void> + */ + + @DELETE("user/{username}") + F.Promise> deleteUser( + @retrofit2.http.Path("username") String username + ); + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return Call<User> + */ + + @GET("user/{username}") + F.Promise> getUserByName( + @retrofit2.http.Path("username") String username + ); + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return Call<String> + */ + + @GET("user/login") + F.Promise> loginUser( + @retrofit2.http.Query("username") String username, @retrofit2.http.Query("password") String password + ); + + /** + * Logs out current logged in user session + * + * @return Call<Void> + */ + + @GET("user/logout") + F.Promise> logoutUser(); + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return Call<Void> + */ + + @PUT("user/{username}") + F.Promise> updateUser( + @retrofit2.http.Path("username") String username, @retrofit2.http.Body User body + ); + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..9813f3782b4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,78 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +/** + * Holds ApiKey auth info + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + 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; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..e40d7ff7002 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,29 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..3afefc1400a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,126 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * AdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java new file mode 100644 index 00000000000..8e8c3e545f4 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java @@ -0,0 +1,119 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Animal + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00")@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonSubTypes({ + @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +}) +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @NotNull + @ApiModelProperty(example = "null", required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(example = "null", value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java new file mode 100644 index 00000000000..2cb88837116 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -0,0 +1,66 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import io.swagger.client.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * AnimalFarm + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..92019105325 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,98 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..24360a2bdc7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,98 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java new file mode 100644 index 00000000000..20eab555096 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java @@ -0,0 +1,154 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayTest + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java new file mode 100644 index 00000000000..207def80da6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java @@ -0,0 +1,92 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import javax.validation.constraints.*; + +/** + * Cat + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 00000000000..c964038f6ff --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,113 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Category + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java new file mode 100644 index 00000000000..c3274ac78be --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java @@ -0,0 +1,91 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java new file mode 100644 index 00000000000..5b58d26ba1e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Client + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(example = "null", value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java new file mode 100644 index 00000000000..e83c9b37d30 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java @@ -0,0 +1,92 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import javax.validation.constraints.*; + +/** + * Dog + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(example = "null", value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java new file mode 100644 index 00000000000..26f73036657 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java @@ -0,0 +1,180 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * EnumArrays + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(example = "null", value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(example = "null", value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumClass.java new file mode 100644 index 00000000000..d18c22b5eee --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumClass.java @@ -0,0 +1,53 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java new file mode 100644 index 00000000000..c900eff8ea0 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java @@ -0,0 +1,250 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.OuterEnum; +import javax.validation.constraints.*; + +/** + * EnumTest + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(example = "null", value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(example = "null", value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java new file mode 100644 index 00000000000..feb6b20074d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java @@ -0,0 +1,395 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import javax.validation.constraints.*; + +/** + * FormatTest + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10.0 + * maximum: 100.0 + * @return integer + **/ + //@Min(10.0) + //@Max(100.0) + @ApiModelProperty(example = "null", value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20.0 + * maximum: 200.0 + * @return int32 + **/ + //@Min(20.0) + //@Max(200.0) + @ApiModelProperty(example = "null", value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(example = "null", value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @NotNull + //@Min(32.1) + //@Max(543.2) + @ApiModelProperty(example = "null", required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + //@Min(54.3) + //@Max(987.6) + @ApiModelProperty(example = "null", value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + //@Min(67.8) + //@Max(123.4) + @ApiModelProperty(example = "null", value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @Pattern(regexp="/[a-z]/i") + @ApiModelProperty(example = "null", value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @NotNull + @ApiModelProperty(example = "null", required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(example = "null", value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @NotNull + @ApiModelProperty(example = "null", required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @NotNull + @Size(min=10,max=64) + @ApiModelProperty(example = "null", required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..88c6c5daef7 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -0,0 +1,95 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * HasOnlyReadOnly + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java new file mode 100644 index 00000000000..f1ac43cfeb1 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java @@ -0,0 +1,156 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * MapTest + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..993fdd826e6 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,146 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; +import javax.validation.constraints.*; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(example = "null", value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(example = "null", value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java new file mode 100644 index 00000000000..caf31c62d3b --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java @@ -0,0 +1,114 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..7544637df88 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -0,0 +1,136 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ModelApiResponse + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(example = "null", value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(example = "null", value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java new file mode 100644 index 00000000000..1956bf7b06a --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java @@ -0,0 +1,91 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java new file mode 100644 index 00000000000..e72f4a8c43b --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java @@ -0,0 +1,143 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + @ApiModelProperty(example = "null", required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(example = "null", value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java new file mode 100644 index 00000000000..7e469875219 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java @@ -0,0 +1,91 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; + +/** + * NumberOnly + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 00000000000..b4f2b763815 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,238 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; +import javax.validation.constraints.*; + +/** + * Order + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(example = "null", value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(example = "null", value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(example = "null", value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(example = "null", value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/OuterEnum.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/OuterEnum.java new file mode 100644 index 00000000000..444a63a6179 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/OuterEnum.java @@ -0,0 +1,53 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 00000000000..b06e91307ed --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,253 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * Pet + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(example = "null", value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @NotNull + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @NotNull + @ApiModelProperty(example = "null", required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(example = "null", value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(example = "null", value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..0802150574e --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -0,0 +1,104 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ReadOnlyFirst + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(example = "null", value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java new file mode 100644 index 00000000000..e2b972912b5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * SpecialModelName + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(example = "null", value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 00000000000..d7c65f1089f --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,113 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Tag + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 00000000000..e83a62dcb0c --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,251 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * User + */ +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(example = "null", value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(example = "null", value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(example = "null", value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(example = "null", value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(example = "null", value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(example = "null", value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(example = "null", value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/FakeApiTest.java new file mode 100644 index 00000000000..ab4b7c2c53d --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -0,0 +1,88 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + private FakeApi api; + + @Before + public void setup() { + api = new ApiClient().createService(FakeApi.class); + } + + + /** + * To test \"client\" model + * + * + */ + @Test + public void testClientModelTest() { + Client body = null; + // Client response = api.testClientModel(body); + + // TODO: test validations + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + byte[] binary = null; + LocalDate date = null; + DateTime dateTime = null; + String password = null; + String paramCallback = null; + // Void response = api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + + // TODO: test validations + } + + /** + * To test enum parameters + * + * + */ + @Test + public void testEnumParametersTest() { + List enumFormStringArray = null; + String enumFormString = null; + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + BigDecimal enumQueryInteger = null; + Double enumQueryDouble = null; + // Void response = api.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/PetApiTest.java new file mode 100644 index 00000000000..a3688eb35c5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/PetApiTest.java @@ -0,0 +1,137 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private PetApi api; + + @Before + public void setup() { + api = new ApiClient().createService(PetApi.class); + } + + + /** + * Add a new pet to the store + * + * + */ + @Test + public void addPetTest() { + Pet body = null; + // Void response = api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + // Void response = api.deletePet(petId, apiKey); + + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + */ + @Test + public void findPetsByStatusTest() { + List status = null; + // List response = api.findPetsByStatus(status); + + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + // List response = api.findPetsByTags(tags); + + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + */ + @Test + public void getPetByIdTest() { + Long petId = null; + // Pet response = api.getPetById(petId); + + // TODO: test validations + } + + /** + * Update an existing pet + * + * + */ + @Test + public void updatePetTest() { + Pet body = null; + // Void response = api.updatePet(body); + + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + // Void response = api.updatePetWithForm(petId, name, status); + + // TODO: test validations + } + + /** + * uploads an image + * + * + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + File file = null; + // ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/StoreApiTest.java new file mode 100644 index 00000000000..1da787edf19 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -0,0 +1,77 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.Order; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + private StoreApi api; + + @Before + public void setup() { + api = new ApiClient().createService(StoreApi.class); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + */ + @Test + public void deleteOrderTest() { + String orderId = null; + // Void response = api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + */ + @Test + public void getInventoryTest() { + // Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + // Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + */ + @Test + public void placeOrderTest() { + Order body = null; + // Order response = api.placeOrder(body); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/UserApiTest.java new file mode 100644 index 00000000000..cd8553d8419 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/test/java/io/swagger/client/api/UserApiTest.java @@ -0,0 +1,131 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiClient; +import io.swagger.client.model.User; +import org.junit.Before; +import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UserApi + */ +public class UserApiTest { + + private UserApi api; + + @Before + public void setup() { + api = new ApiClient().createService(UserApi.class); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + */ + @Test + public void createUserTest() { + User body = null; + // Void response = api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + // Void response = api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + // Void response = api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + */ + @Test + public void deleteUserTest() { + String username = null; + // Void response = api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * + */ + @Test + public void getUserByNameTest() { + String username = null; + // User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + // String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + */ + @Test + public void logoutUserTest() { + // Void response = api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + // Void response = api.updateUser(username, body); + + // TODO: test validations + } + +} From a143e9c10c08722303f8d36a4e720e0762105aa3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 14 Dec 2016 22:21:52 +0800 Subject: [PATCH 172/269] add int/long check for @min/@max in java model (#4395) --- .../resources/Java/beanValidation.mustache | 12 +- .../petstore/java/okhttp-gson/docs/FakeApi.md | 8 +- .../petstore/java/okhttp-gson/git_push.sh | 6 +- .../client/petstore/java/okhttp-gson/pom.xml | 2 +- .../java/io/swagger/client/ApiCallback.java | 2 +- .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/ApiException.java | 4 +- .../java/io/swagger/client/ApiResponse.java | 2 +- .../java/io/swagger/client/Configuration.java | 4 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 4 +- .../swagger/client/ProgressRequestBody.java | 2 +- .../swagger/client/ProgressResponseBody.java | 2 +- .../java/io/swagger/client/StringUtil.java | 4 +- .../java/io/swagger/client/api/FakeApi.java | 981 ++++---- .../java/io/swagger/client/api/PetApi.java | 2011 +++++++++-------- .../java/io/swagger/client/api/StoreApi.java | 1014 ++++----- .../java/io/swagger/client/api/UserApi.java | 1956 ++++++++-------- .../io/swagger/client/auth/ApiKeyAuth.java | 4 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 4 +- .../io/swagger/client/auth/OAuthFlow.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 2 +- .../io/swagger/client/model/Category.java | 7 +- .../io/swagger/client/model/FormatTest.java | 8 +- .../client/model/ModelApiResponse.java | 7 +- .../java/io/swagger/client/model/Order.java | 7 +- .../java/io/swagger/client/model/Pet.java | 7 +- .../java/io/swagger/client/model/Tag.java | 7 +- .../java/io/swagger/client/model/User.java | 7 +- .../java/retrofit2-play24/docs/FakeApi.md | 10 +- .../java/retrofit2-play24/docs/PetApi.md | 2 +- .../java/retrofit2-play24/docs/StoreApi.md | 2 +- .../java/retrofit2-play24/docs/UserApi.md | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/FakeApi.java | 6 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 +- .../java/io/swagger/client/model/Animal.java | 2 +- .../io/swagger/client/model/AnimalFarm.java | 4 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 2 +- .../java/io/swagger/client/model/Cat.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../io/swagger/client/model/ClassModel.java | 2 +- .../java/io/swagger/client/model/Client.java | 2 +- .../java/io/swagger/client/model/Dog.java | 2 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/EnumTest.java | 2 +- .../io/swagger/client/model/FormatTest.java | 24 +- .../swagger/client/model/HasOnlyReadOnly.java | 2 +- .../java/io/swagger/client/model/MapTest.java | 2 +- ...ropertiesAndAdditionalPropertiesClass.java | 2 +- .../client/model/Model200Response.java | 2 +- .../client/model/ModelApiResponse.java | 2 +- .../io/swagger/client/model/ModelReturn.java | 2 +- .../java/io/swagger/client/model/Name.java | 2 +- .../io/swagger/client/model/NumberOnly.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/model/ReadOnlyFirst.java | 2 +- .../client/model/SpecialModelName.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- 67 files changed, 3128 insertions(+), 3064 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache index f13ed596859..891a94b3ba1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -35,8 +35,18 @@ {{/maxItems}} {{/minItems}} {{#minimum}} + {{#isInteger}} @Min({{minimum}}) + {{/isInteger}} + {{#isLong}} + @Min({{minimum}}) + {{/isLong}} {{/minimum}} {{#maximum}} + {{#isInteger}} @Max({{maximum}}) -{{/maximum}} \ No newline at end of file + {{/isInteger}} + {{#isLong}} + @Max({{maximum}}) + {{/isLong}} +{{/maximum}} diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 129605dbf8a..284ae074be9 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -137,6 +139,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -151,7 +155,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -171,7 +175,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/okhttp-gson/git_push.sh b/samples/client/petstore/java/okhttp-gson/git_push.sh index 6ca091b49d9..ed374619b13 100644 --- a/samples/client/petstore/java/okhttp-gson/git_push.sh +++ b/samples/client/petstore/java/okhttp-gson/git_push.sh @@ -8,17 +8,17 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi if [ "$release_note" = "" ]; then - release_note="" + release_note="Minor update" echo "[INFO] No command line input provided. Set \$release_note to $release_note" fi diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index d6ce1873282..b7743d77d81 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -129,7 +129,7 @@ joda-time ${jodatime-version}
    - + junit diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index a93b4b86434..be36cd4675d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index bc1cc3da29a..d014d7d4035 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index 1cfe6833639..d0b5cfc1e57 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -16,7 +16,7 @@ package io.swagger.client; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java index e2e8e7e490e..6baa9120c69 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiResponse.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index b95d9c78183..cbf868efb85 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 33696a2ae12..5692584772f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index 0d46b6e9cb5..b75cd316ac1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java index 2b09fa4d9d6..a06ea04a4d0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressRequestBody.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java index f6358f5e017..48c4bfa92d5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ProgressResponseBody.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index b9f48b3e18a..339a3fb36d5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 9024544c8eb..bb897d07d80 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,475 +9,512 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - -import java.math.BigDecimal; -import io.swagger.client.model.Client; -import org.joda.time.DateTime; -import org.joda.time.LocalDate; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testClientModel */ - private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test \"client\" model - * - * @param body client model (required) - * @return Client - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Client testClientModel(Client body) throws ApiException { - ApiResponse resp = testClientModelWithHttpInfo(body); - return resp.getData(); - } - - /** - * To test \"client\" model - * - * @param body client model (required) - * @return ApiResponse<Client> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { - com.squareup.okhttp.Call call = testClientModelCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * To test \"client\" model (asynchronously) - * - * @param body client model (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'patternWithoutDelimiter' is set - if (patternWithoutDelimiter == null) { - throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (patternWithoutDelimiter != null) - localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - if (paramCallback != null) - localVarFormParams.put("callback", paramCallback); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "http_basic_test" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumParameters */ - private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryStringArray != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); - if (enumQueryString != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - if (enumHeaderStringArray != null) - localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); - if (enumHeaderString != null) - localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); - - Map localVarFormParams = new HashMap(); - if (enumFormStringArray != null) - localVarFormParams.put("enum_form_string_array", enumFormStringArray); - if (enumFormString != null) - localVarFormParams.put("enum_form_string", enumFormString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "*/*" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "*/*" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test enum parameters - * - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); - } - - /** - * To test enum parameters - * - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); - } - - /** - * To test enum parameters (asynchronously) - * - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testClientModel */ + private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); + } + + + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Client testClientModel(Client body) throws ApiException { + ApiResponse resp = testClientModelWithHttpInfo(body); + return resp.getData(); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * To test \"client\" model + * @param body client model (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, DateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumParameters */ + private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryStringArray != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + if (enumQueryString != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); + if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + Map localVarFormParams = new HashMap(); + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "*/*" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum parameters (asynchronously) + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index d1ca65b8b27..d86cc92060b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -9,1003 +9,1012 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - -import java.io.File; -import io.swagger.client.model.ModelApiResponse; -import io.swagger.client.model.Pet; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * Finds Pets by status - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by status (asynchronously) - * Multiple status values can be provided with comma separated strings - * @param status Status values that need to be considered for filter (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Finds Pets by tags (asynchronously) - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * @param tags Tags to filter by (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index 6ee4aea1266..e2c41fa1aa5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -9,507 +9,511 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.Order; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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 (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - deleteOrderWithHttpInfo(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 (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * Delete purchase order by ID (asynchronously) - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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 (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * 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 (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find purchase order by ID (asynchronously) - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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 (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(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 (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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 (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * 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 (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index a6ec29605b2..d79a19a65ca 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -9,976 +9,984 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.User; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 4110dfbe15b..5c6925473e5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -18,7 +18,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index ef200f1ed30..e40d7ff7002 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 7e7aa0d67c2..b16049cf4a3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index 088a38eef3b..2d9dc9da8b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -18,7 +18,7 @@ import io.swagger.client.Pair; import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class OAuth implements Authentication { private String accessToken; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java index bfb1e1c4501..b3718a0643c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java index 275d0f17175..db1dc0c9008 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -19,10 +19,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** - * A category for a pet + * Category */ -@ApiModel(description = "A category for a pet") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Category { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 4bca9018689..287c083b188 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -72,8 +72,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -92,8 +92,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java index 97b1c7d98ee..5af5c68f073 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -19,10 +19,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** - * Describes the result of uploading an image resource + * ModelApiResponse */ -@ApiModel(description = "Describes the result of uploading an image resource") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class ModelApiResponse { @SerializedName("code") private Integer code = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index 81f6c5110b3..de5cc9a6d3a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -20,10 +20,9 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; /** - * An order for a pets from the pet store + * Order */ -@ApiModel(description = "An order for a pets from the pet store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Order { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 69d7437c9d2..3d0ee70b1b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -23,10 +23,9 @@ import java.util.ArrayList; import java.util.List; /** - * A pet for sale in the pet store + * Pet */ -@ApiModel(description = "A pet for sale in the pet store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Pet { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java index 8d5b8d76004..c53f7ceb050 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -19,10 +19,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** - * A tag for a pet + * Tag */ -@ApiModel(description = "A tag for a pet") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class Tag { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java index 95459ef9f53..19635b3b5b0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -1,6 +1,6 @@ /* * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * OpenAPI spec version: 1.0.0 * Contact: apiteam@swagger.io @@ -19,10 +19,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** - * A User who is purchasing from the pet store + * User */ -@ApiModel(description = "A User who is purchasing from the pet store") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-11-12T23:31:10.007+01:00") + public class User { @SerializedName("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md index bbd8da9fcc4..d1f45eda4d4 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/FakeApi.md @@ -1,6 +1,6 @@ # FakeApi -All URIs are relative to ** +All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -138,6 +140,8 @@ Name | Type | Description | Notes To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -152,7 +156,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -173,7 +177,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md b/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md index 34ec23fc955..211f5be5fa8 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/PetApi.md @@ -1,6 +1,6 @@ # PetApi -All URIs are relative to ** +All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md b/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md index 14b930e6534..30e3c11d440 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/StoreApi.md @@ -1,6 +1,6 @@ # StoreApi -All URIs are relative to ** +All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md b/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md index e8adef94ea9..b0a0149a50a 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/UserApi.md @@ -1,6 +1,6 @@ # UserApi -All URIs are relative to ** +All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java index bde870aaa4f..332e1f4e224 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java index a52cbe680ac..999ca1fd386 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java index 26c1576fa07..3dec8d367e7 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/FakeApi.java @@ -24,7 +24,7 @@ import retrofit2.Response; public interface FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Call<Client> */ @@ -65,7 +65,7 @@ public interface FakeApi { /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -80,7 +80,7 @@ public interface FakeApi { @retrofit2.http.FormUrlEncoded @GET("fake") F.Promise> testEnumParameters( - @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 9813f3782b4..c5b84a1b8fd 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -21,7 +21,7 @@ import java.util.List; /** * Holds ApiKey auth info */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 3afefc1400a..909c30a1b03 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * AdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class AdditionalPropertiesClass { @JsonProperty("map_property") private Map mapProperty = new HashMap(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java index 8e8c3e545f4..ab1400635b3 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java @@ -25,7 +25,7 @@ import javax.validation.constraints.*; /** * Animal */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00")@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00")@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), }) diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java index 2cb88837116..6529f902150 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -22,7 +22,7 @@ import javax.validation.constraints.*; /** * AnimalFarm */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class AnimalFarm extends ArrayList { @Override @@ -33,7 +33,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index 92019105325..f0eaa2635f0 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ArrayOfArrayOfNumberOnly { @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 24360a2bdc7..4e76d18065b 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayOfNumberOnly */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ArrayOfNumberOnly { @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java index 20eab555096..7b6dda6f0e8 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ArrayTest { @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java index 207def80da6..86a61a22cda 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Cat */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Cat extends Animal { @JsonProperty("declawed") private Boolean declawed = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java index c964038f6ff..9a8c766c6c0 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Category */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Category { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java index c3274ac78be..81efcdee6ca 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model with \"_class\" property */ @ApiModel(description = "Model for testing model with \"_class\" property") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ClassModel { @JsonProperty("_class") private String propertyClass = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java index 5b58d26ba1e..489af709c19 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Client */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Client { @JsonProperty("client") private String client = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java index e83c9b37d30..c3e700c72fb 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Dog */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Dog extends Animal { @JsonProperty("breed") private String breed = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java index 26f73036657..116c874f765 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java @@ -25,7 +25,7 @@ import javax.validation.constraints.*; /** * EnumArrays */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class EnumArrays { /** * Gets or Sets justSymbol diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java index c900eff8ea0..d14bf8cc76e 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * EnumTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class EnumTest { /** * Gets or Sets enumString diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java index feb6b20074d..a249c4b5b96 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * FormatTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class FormatTest { @JsonProperty("integer") private Integer integer = null; @@ -74,12 +74,12 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ - //@Min(10.0) - //@Max(100.0) + @Min(10) + @Max(100) @ApiModelProperty(example = "null", value = "") public Integer getInteger() { return integer; @@ -96,12 +96,12 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ - //@Min(20.0) - //@Max(200.0) + @Min(20) + @Max(200) @ApiModelProperty(example = "null", value = "") public Integer getInt32() { return int32; @@ -141,8 +141,6 @@ public class FormatTest { * @return number **/ @NotNull - //@Min(32.1) - //@Max(543.2) @ApiModelProperty(example = "null", required = true, value = "") public BigDecimal getNumber() { return number; @@ -163,8 +161,6 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ - //@Min(54.3) - //@Max(987.6) @ApiModelProperty(example = "null", value = "") public Float getFloat() { return _float; @@ -185,8 +181,6 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ - //@Min(67.8) - //@Max(123.4) @ApiModelProperty(example = "null", value = "") public Double getDouble() { return _double; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index 88c6c5daef7..3ee7b857530 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * HasOnlyReadOnly */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class HasOnlyReadOnly { @JsonProperty("bar") private String bar = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java index f1ac43cfeb1..ff9e95d36a8 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * MapTest */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class MapTest { @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 993fdd826e6..84f3bf1791a 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -28,7 +28,7 @@ import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") private String uuid = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java index caf31c62d3b..1c7e6e4ae71 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Model200Response { @JsonProperty("name") private Integer name = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java index 7544637df88..e37ed10f305 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ModelApiResponse { @JsonProperty("code") private Integer code = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java index 1956bf7b06a..b50a1f7338c 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ModelReturn { @JsonProperty("return") private Integer _return = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java index e72f4a8c43b..7b44370f3d2 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Name { @JsonProperty("name") private Integer name = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java index 7e469875219..e48dbe99417 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * NumberOnly */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class NumberOnly { @JsonProperty("JustNumber") private BigDecimal justNumber = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java index b4f2b763815..dcb7f9264f3 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Order */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Order { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java index b06e91307ed..7bc5658cef7 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java @@ -27,7 +27,7 @@ import javax.validation.constraints.*; /** * Pet */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Pet { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 0802150574e..349de2635ad 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * ReadOnlyFirst */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class ReadOnlyFirst { @JsonProperty("bar") private String bar = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java index e2b972912b5..a5a05393b4a 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * SpecialModelName */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class SpecialModelName { @JsonProperty("$special[property.name]") private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java index d7c65f1089f..da3d48cc49f 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Tag */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class Tag { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java index e83a62dcb0c..d0143c1e4aa 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * User */ -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-09T01:19:10.790+04:00") +@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") public class User { @JsonProperty("id") private Long id = null; From f63d9622583cb898d8fde51dc40969137a396e90 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 15 Dec 2016 00:42:08 +0800 Subject: [PATCH 173/269] update ts angular2 sample --- .../typescript-angular2/default/api/PetApi.ts | 12 +++--- .../default/api/StoreApi.ts | 2 +- .../default/api/UserApi.ts | 2 +- .../typescript-angular2/npm/README.md | 4 +- .../typescript-angular2/npm/api/PetApi.ts | 40 +++++++++++++++---- .../typescript-angular2/npm/configuration.ts | 2 +- .../typescript-angular2/npm/package.json | 2 +- 7 files changed, 44 insertions(+), 20 deletions(-) diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index f63e11ad793..3b3a5503a67 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class PetApi { - protected basePath = ''; + protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); @@ -427,6 +427,11 @@ export class PetApi { 'application/xml' ]; + // authentication (api_key) required + if (this.configuration.apiKey) + { + headers.set('api_key', this.configuration.apiKey); + } // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) @@ -436,11 +441,6 @@ export class PetApi { : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 0128163445f..484d5e56fde 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class StoreApi { - protected basePath = ''; + protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index c47d4cb0310..8dda0cf8377 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -27,7 +27,7 @@ import { Configuration } from '../configurat @Injectable() export class UserApi { - protected basePath = ''; + protected basePath = 'http://petstore.swagger.io/v2'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 1c4f0c5bd4f..5f176a7b484 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612150011 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612061134 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612150011 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 70ab123c5a5..3b3a5503a67 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -217,7 +217,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -271,7 +274,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -320,7 +326,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -369,7 +378,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -424,7 +436,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -472,7 +487,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } @@ -529,7 +547,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } headers.set('Content-Type', 'application/x-www-form-urlencoded'); @@ -592,7 +613,10 @@ export class PetApi { // oauth required if (this.configuration.accessToken) { - headers.set('Authorization', 'Bearer ' + this.configuration.accessToken); + let accessToken = typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken() + : this.configuration.accessToken; + headers.set('Authorization', 'Bearer ' + accessToken); } headers.set('Content-Type', 'application/x-www-form-urlencoded'); diff --git a/samples/client/petstore/typescript-angular2/npm/configuration.ts b/samples/client/petstore/typescript-angular2/npm/configuration.ts index 94989933b63..a566a180e4e 100644 --- a/samples/client/petstore/typescript-angular2/npm/configuration.ts +++ b/samples/client/petstore/typescript-angular2/npm/configuration.ts @@ -2,5 +2,5 @@ export class Configuration { apiKey: string; username: string; password: string; - accessToken: string; + accessToken: string | (() => string); } \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index eeeca81bcbb..6dd91bb3f86 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201612061134", + "version": "0.0.1-SNAPSHOT.201612150011", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ From 3bc3a40073ab7a801766261d5f795da584d8d53a Mon Sep 17 00:00:00 2001 From: Cliffano Subagio Date: Tue, 13 Dec 2016 16:55:31 +1100 Subject: [PATCH 174/269] [java] Add licenseName and licenseUrl options. --- .../io/swagger/codegen/CodegenConstants.java | 21 +++++++----- .../languages/AbstractJavaCodegen.java | 28 +++++++++++++-- .../Java/libraries/feign/pom.mustache | 8 +++++ .../Java/libraries/jersey2/pom.mustache | 8 +++++ .../Java/libraries/okhttp-gson/pom.mustache | 17 +++++++--- .../Java/libraries/retrofit/pom.mustache | 8 +++++ .../Java/libraries/retrofit2/pom.mustache | 8 +++++ .../src/main/resources/Java/pom.mustache | 12 +++++-- .../main/resources/JavaInflector/pom.mustache | 10 +++++- .../src/main/resources/JavaJaxRS/pom.mustache | 9 +++++ .../codegen/java/JavaClientOptionsTest.java | 34 ++++++++++--------- .../codegen/options/JavaOptionsProvider.java | 4 +++ .../options/JaxRSServerOptionsProvider.java | 4 +++ 13 files changed, 137 insertions(+), 34 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 7a10c3f3ac6..84c5c9e8714 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -25,12 +25,18 @@ public class CodegenConstants { public static final String ARTIFACT_VERSION = "artifactVersion"; public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml"; + public static final String LICENSE_NAME = "licenseName"; + public static final String LICENSE_NAME_DESC = "The name of the license"; + + public static final String LICENSE_URL = "licenseUrl"; + public static final String LICENSE_URL_DESC = "The URL of the license"; + public static final String SOURCE_FOLDER = "sourceFolder"; public static final String SOURCE_FOLDER_DESC = "source folder for generated code"; public static final String IMPL_FOLDER = "implFolder"; public static final String IMPL_FOLDER_DESC = "folder for generated implementation code"; - + public static final String LOCAL_VARIABLE_PREFIX = "localVariablePrefix"; public static final String LOCAL_VARIABLE_PREFIX_DESC = "prefix for generated code members and local variables"; @@ -48,13 +54,13 @@ public class CodegenConstants { public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; - + public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; public static final String PACKAGE_NAME = "packageName"; public static final String PACKAGE_VERSION = "packageVersion"; - + public static final String PACKAGE_TITLE = "packageTitle"; public static final String PACKAGE_TITLE_DESC = "Specifies an AssemblyTitle for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_PRODUCTNAME = "packageProductName"; @@ -65,7 +71,7 @@ public class CodegenConstants { public static final String PACKAGE_COMPANY_DESC = "Specifies an AssemblyCompany for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; public static final String PACKAGE_COPYRIGHT = "packageCopyright"; public static final String PACKAGE_COPYRIGHT_DESC = "Specifies an AssemblyCopyright for the .NET Framework global assembly attributes stored in the AssemblyInfo file."; - + public static final String POD_VERSION = "podVersion"; public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; @@ -79,13 +85,13 @@ public class CodegenConstants { public static final String RETURN_ICOLLECTION = "returnICollection"; public static final String RETURN_ICOLLECTION_DESC = "Return ICollection instead of the concrete type."; - + public static final String OPTIONAL_PROJECT_FILE = "optionalProjectFile"; public static final String OPTIONAL_PROJECT_FILE_DESC = "Generate {PackageName}.csproj."; - + public static final String OPTIONAL_PROJECT_GUID = "packageGuid"; public static final String OPTIONAL_PROJECT_GUID_DESC = "The GUID that will be associated with the C# project"; - + public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; public static final String MODEL_PROPERTY_NAMING_DESC = "Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name"; @@ -132,5 +138,4 @@ public class CodegenConstants { public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged"; public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; - } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 2fb928e4c49..32c4a51f3ad 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -52,6 +52,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected String groupId = "io.swagger"; protected String artifactId = "swagger-java"; protected String artifactVersion = "1.0.0"; + protected String licenseName = "Apache License, Version 2.0"; + protected String licenseUrl = "http://www.apache.org/licenses/LICENSE-2.0"; protected String projectFolder = "src" + File.separator + "main"; protected String projectTestFolder = "src" + File.separator + "test"; protected String sourceFolder = projectFolder + File.separator + "java"; @@ -117,6 +119,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC)); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(CliOption.newBoolean(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); @@ -187,6 +191,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } + if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) { + this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME)); + } else { + additionalProperties.put(CodegenConstants.LICENSE_NAME, licenseName); + } + + if (additionalProperties.containsKey(CodegenConstants.LICENSE_URL)) { + this.setLicenseUrl((String) additionalProperties.get(CodegenConstants.LICENSE_URL)); + } else { + additionalProperties.put(CodegenConstants.LICENSE_URL, licenseUrl); + } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)) { this.setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); } @@ -821,7 +837,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code op.path = sanitizePath(op.path); return op; } - + private static CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze @@ -895,6 +911,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.artifactVersion = artifactVersion; } + public void setLicenseName(String licenseName) { + this.licenseName = licenseName; + } + + public void setLicenseUrl(String licenseUrl) { + this.licenseUrl = licenseUrl; + } + public void setSourceFolder(String sourceFolder) { this.sourceFolder = sourceFolder; } @@ -957,7 +981,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } return sb.toString(); } - + public void setSupportJava6(boolean value) { this.supportJava6 = value; } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 11fc2dea148..0b464a31b02 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -15,6 +15,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index 3674b6072c5..5c51b9cd677 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -15,6 +15,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index 4e2e7e877c8..b34c3856f4d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -15,6 +15,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + @@ -131,7 +139,7 @@ ${jodatime-version} {{/java8}} - {{#useBeanValidation}} + {{#useBeanValidation}} javax.validation @@ -139,8 +147,8 @@ 1.1.0.Final provided - {{/useBeanValidation}} - {{#performBeanValidation}} + {{/useBeanValidation}} + {{#performBeanValidation}} org.hibernate @@ -153,7 +161,6 @@ 2.2 {{/performBeanValidation}} - junit @@ -174,4 +181,4 @@ 4.12 UTF-8 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index c816526cd59..e38068e27b2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -15,6 +15,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index 474f980a020..5f2d74d3c53 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -15,6 +15,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 9bd93ccd5e9..30d9b7bb839 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -11,6 +11,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + @@ -194,7 +202,7 @@ ${commons_io_version} {{/supportJava6}} -{{#useBeanValidation}} +{{#useBeanValidation}} javax.validation @@ -202,7 +210,7 @@ 1.1.0.Final provided -{{/useBeanValidation}} +{{/useBeanValidation}} junit diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache index 5b6b7c0161d..4d7bc8c2647 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pom.mustache @@ -14,6 +14,14 @@ 2.2.0 + + + {{licenseName}} + {{licenseUrl}} + repo + + + install target @@ -117,4 +125,4 @@ 4.8.2 1.6.3 - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 03582826a58..19cbd0a95ad 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -5,6 +5,15 @@ jar {{artifactId}} {{artifactVersion}} + + + + {{licenseName}} + {{licenseUrl}} + repo + + + src/main/java diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index 3fdd9756e82..413b61c3e00 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -32,36 +32,38 @@ public class JavaClientOptionsTest extends AbstractOptionsTest { @Override protected void setExpectations() { new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE); + clientCodegen.setModelPackage(JavaClientOptionsProvider.MODEL_PACKAGE_VALUE); times = 1; - clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE); + clientCodegen.setApiPackage(JavaClientOptionsProvider.API_PACKAGE_VALUE); times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(JavaClientOptionsProvider.SORT_PARAMS_VALUE)); times = 1; - clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE); + clientCodegen.setInvokerPackage(JavaClientOptionsProvider.INVOKER_PACKAGE_VALUE); times = 1; - clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE); + clientCodegen.setGroupId(JavaClientOptionsProvider.GROUP_ID_VALUE); times = 1; - clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE); + clientCodegen.setArtifactId(JavaClientOptionsProvider.ARTIFACT_ID_VALUE); times = 1; - clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); + clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; - clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE); + clientCodegen.setLicenseName(JavaOptionsProvider.LICENSE_NAME_VALUE); times = 1; - clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); + clientCodegen.setLicenseUrl(JavaOptionsProvider.LICENSE_URL_VALUE); times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + clientCodegen.setSourceFolder(JavaOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(JavaClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; clientCodegen.setLibrary(JavaClientOptionsProvider.DEFAULT_LIBRARY_VALUE); times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); + clientCodegen.setFullJavaUtil(Boolean.valueOf(JavaClientOptionsProvider.FULL_JAVA_UTIL_VALUE)); times = 1; - // clientCodegen.setSupportJava6(Boolean.valueOf(JavaClientOptionsProvider.SUPPORT_JAVA6)); - //times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION)); + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.USE_BEANVALIDATION)); + times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); times = 1; - clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaClientOptionsProvider.PERFORM_BEANVALIDATION)); - times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 15a553d53b3..9fe39cc95d3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -11,6 +11,8 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String MODEL_PACKAGE_VALUE = "package"; public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; + public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; + public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; @@ -37,6 +39,8 @@ public class JavaOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) + .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index 3db594f94b8..57896db9ca6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -14,6 +14,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; + public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String LOCAL_PREFIX_VALUE = "tst"; public static final String DEFAULT_LIBRARY_VALUE = "jersey2"; @@ -49,6 +51,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) + .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .put(CodegenConstants.LOCAL_VARIABLE_PREFIX, LOCAL_PREFIX_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) From 870c745e6f4a22f2701aafec95c8ea578d5aa880 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 15 Dec 2016 19:16:02 +0800 Subject: [PATCH 175/269] minor fix to java client options test --- .../java/io/swagger/codegen/java/JavaClientOptionsTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index 413b61c3e00..ec1bc951f38 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -46,11 +46,11 @@ public class JavaClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; - clientCodegen.setLicenseName(JavaOptionsProvider.LICENSE_NAME_VALUE); + clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE); times = 1; - clientCodegen.setLicenseUrl(JavaOptionsProvider.LICENSE_URL_VALUE); + clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE); times = 1; - clientCodegen.setSourceFolder(JavaOptionsProvider.SOURCE_FOLDER_VALUE); + clientCodegen.setSourceFolder(JavaClientOptionsProvider.SOURCE_FOLDER_VALUE); times = 1; clientCodegen.setLocalVariablePrefix(JavaClientOptionsProvider.LOCAL_PREFIX_VALUE); times = 1; From 131cbeb350b6d8be20d73a1f34b93f93f8d2ccb4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 15 Dec 2016 19:34:15 +0800 Subject: [PATCH 176/269] remove generation timestamp --- bin/java-petstore-retrofit2-play24.sh | 2 +- .../codegen/languages/AbstractJavaCodegen.java | 4 ++-- .../main/resources/Java/libraries/feign/pom.mustache | 2 +- samples/client/petstore/java/feign/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 6 +++--- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- samples/client/petstore/java/jersey1/docs/FakeApi.md | 8 ++++++-- samples/client/petstore/java/jersey1/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 6 +++--- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- .../petstore/java/jersey2-java8/docs/FakeApi.md | 8 ++++++-- samples/client/petstore/java/jersey2-java8/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 6 +++--- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- samples/client/petstore/java/jersey2/docs/FakeApi.md | 8 ++++++-- samples/client/petstore/java/jersey2/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 6 +++--- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- samples/client/petstore/java/okhttp-gson/pom.xml | 11 +++++++++-- samples/client/petstore/java/retrofit/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 8 ++++---- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- samples/client/petstore/java/retrofit2-play24/pom.xml | 8 ++++++++ .../src/main/java/io/swagger/client/Pair.java | 2 +- .../src/main/java/io/swagger/client/StringUtil.java | 2 +- .../main/java/io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../client/model/AdditionalPropertiesClass.java | 2 +- .../src/main/java/io/swagger/client/model/Animal.java | 2 +- .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../client/model/ArrayOfArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayOfNumberOnly.java | 2 +- .../main/java/io/swagger/client/model/ArrayTest.java | 2 +- .../src/main/java/io/swagger/client/model/Cat.java | 2 +- .../main/java/io/swagger/client/model/Category.java | 2 +- .../main/java/io/swagger/client/model/ClassModel.java | 2 +- .../src/main/java/io/swagger/client/model/Client.java | 2 +- .../src/main/java/io/swagger/client/model/Dog.java | 2 +- .../main/java/io/swagger/client/model/EnumArrays.java | 2 +- .../main/java/io/swagger/client/model/EnumTest.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 2 +- .../java/io/swagger/client/model/HasOnlyReadOnly.java | 2 +- .../main/java/io/swagger/client/model/MapTest.java | 2 +- .../MixedPropertiesAndAdditionalPropertiesClass.java | 2 +- .../io/swagger/client/model/Model200Response.java | 2 +- .../io/swagger/client/model/ModelApiResponse.java | 2 +- .../java/io/swagger/client/model/ModelReturn.java | 2 +- .../src/main/java/io/swagger/client/model/Name.java | 2 +- .../main/java/io/swagger/client/model/NumberOnly.java | 2 +- .../src/main/java/io/swagger/client/model/Order.java | 2 +- .../src/main/java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/ReadOnlyFirst.java | 2 +- .../io/swagger/client/model/SpecialModelName.java | 2 +- .../src/main/java/io/swagger/client/model/Tag.java | 2 +- .../src/main/java/io/swagger/client/model/User.java | 2 +- .../client/petstore/java/retrofit2/docs/FakeApi.md | 8 ++++++-- samples/client/petstore/java/retrofit2/pom.xml | 9 +++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 7 ++++--- .../src/main/java/io/swagger/client/api/PetApi.java | 1 + .../src/main/java/io/swagger/client/api/StoreApi.java | 1 + .../src/main/java/io/swagger/client/api/UserApi.java | 1 + .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- .../client/petstore/java/retrofit2rx/docs/FakeApi.md | 8 ++++++-- samples/client/petstore/java/retrofit2rx/pom.xml | 9 +++++++++ .../src/main/java/io/swagger/client/api/FakeApi.java | 7 ++++--- .../src/main/java/io/swagger/client/api/PetApi.java | 1 + .../src/main/java/io/swagger/client/api/StoreApi.java | 1 + .../src/main/java/io/swagger/client/api/UserApi.java | 1 + .../main/java/io/swagger/client/model/AnimalFarm.java | 2 +- .../main/java/io/swagger/client/model/FormatTest.java | 8 ++++---- 75 files changed, 205 insertions(+), 104 deletions(-) diff --git a/bin/java-petstore-retrofit2-play24.sh b/bin/java-petstore-retrofit2-play24.sh index 43f63fb6251..e95da88199d 100755 --- a/bin/java-petstore-retrofit2-play24.sh +++ b/bin/java-petstore-retrofit2-play24.sh @@ -26,7 +26,7 @@ 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-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2-play24.json -o samples/client/petstore/java/retrofit2-play24" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin/java-petstore-retrofit2-play24.json -o samples/client/petstore/java/retrofit2-play24 -DhideGenerationTimestamp=true" echo "Removing files and folders under samples/client/petstore/java/retrofit2-play24/src/main" rm -rf samples/client/petstore/java/retrofit2-play24/src/main diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 32c4a51f3ad..e33c596c06a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -52,8 +52,8 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected String groupId = "io.swagger"; protected String artifactId = "swagger-java"; protected String artifactVersion = "1.0.0"; - protected String licenseName = "Apache License, Version 2.0"; - protected String licenseUrl = "http://www.apache.org/licenses/LICENSE-2.0"; + protected String licenseName = "Unlicense"; + protected String licenseUrl = "http://unlicense.org"; protected String projectFolder = "src" + File.separator + "main"; protected String projectTestFolder = "src" + File.separator + "test"; protected String sourceFolder = projectFolder + File.separator + "java"; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 0b464a31b02..134e1443da1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -22,7 +22,7 @@ repo - + diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index a5675bb249b..680c521fefd 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index 85ebc213a4e..d387e4786a3 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -19,7 +19,7 @@ public interface FakeApi extends ApiClient.Api { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Client */ @@ -58,7 +58,7 @@ public interface FakeApi extends ApiClient.Api { /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -77,5 +77,5 @@ public interface FakeApi extends ApiClient.Api { "enum_header_string: {enumHeaderString}" }) - void testEnumParameters(@Param("enumFormStringArray") List enumFormStringArray, @Param("enumFormString") String enumFormString, @Param("enumHeaderStringArray") List enumHeaderStringArray, @Param("enumHeaderString") String enumHeaderString, @Param("enumQueryStringArray") List enumQueryStringArray, @Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") BigDecimal enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); + void testEnumParameters(@Param("enumFormStringArray") List enumFormStringArray, @Param("enumFormString") String enumFormString, @Param("enumHeaderStringArray") List enumHeaderStringArray, @Param("enumHeaderString") String enumHeaderString, @Param("enumQueryStringArray") List enumQueryStringArray, @Param("enumQueryString") String enumQueryString, @Param("enumQueryInteger") Integer enumQueryInteger, @Param("enumQueryDouble") Double enumQueryDouble); } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java index cfa92e8bae2..63130ade905 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/FormatTest.java @@ -73,8 +73,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -93,8 +93,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/jersey1/docs/FakeApi.md b/samples/client/petstore/java/jersey1/docs/FakeApi.md index 129605dbf8a..284ae074be9 100644 --- a/samples/client/petstore/java/jersey1/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey1/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -137,6 +139,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -151,7 +155,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -171,7 +175,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml index e40088ac44c..f1cae8b91b6 100644 --- a/samples/client/petstore/java/jersey1/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -11,6 +11,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java index eaa8f60559a..d917239a65e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/FakeApi.java @@ -53,7 +53,7 @@ public class FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Client * @throws ApiException if fails to make API call @@ -190,7 +190,7 @@ if (paramCallback != null) } /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -201,7 +201,7 @@ if (paramCallback != null) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java index cfa92e8bae2..63130ade905 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/FormatTest.java @@ -73,8 +73,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -93,8 +93,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md index fca02c174d1..651c9d0c43f 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -137,6 +139,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -151,7 +155,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -171,7 +175,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index 59cf0ab156d..7e8523783d2 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java index 9078c11804c..7b33209b8cc 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/FakeApi.java @@ -39,7 +39,7 @@ public class FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Client * @throws ApiException if fails to make API call @@ -176,7 +176,7 @@ if (paramCallback != null) } /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -187,7 +187,7 @@ if (paramCallback != null) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java index 974b24022fd..aacde8ace39 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/FormatTest.java @@ -73,8 +73,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -93,8 +93,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/jersey2/docs/FakeApi.md b/samples/client/petstore/java/jersey2/docs/FakeApi.md index 129605dbf8a..284ae074be9 100644 --- a/samples/client/petstore/java/jersey2/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey2/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -137,6 +139,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -151,7 +155,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -171,7 +175,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 4cae9e4ce95..5e8b8375da0 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java index b5df04ea334..1bc9d46a7b6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/FakeApi.java @@ -39,7 +39,7 @@ public class FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Client * @throws ApiException if fails to make API call @@ -176,7 +176,7 @@ if (paramCallback != null) } /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -187,7 +187,7 @@ if (paramCallback != null) * @param enumQueryDouble Query parameter enum test (double) (optional) * @throws ApiException if fails to make API call */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble) throws ApiException { + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { Object localVarPostBody = null; // create path and map variables diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java index cfa92e8bae2..63130ade905 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/FormatTest.java @@ -73,8 +73,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -93,8 +93,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index b7743d77d81..01c90c6076d 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + @@ -129,7 +137,6 @@ joda-time ${jodatime-version} - junit @@ -150,4 +157,4 @@ 4.12 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 2944d770af7..2f3bfa33af4 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 6fc7893c29b..9f0ec47237b 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -20,7 +20,7 @@ public interface FakeApi { /** * To test \"client\" model * Sync method - * + * To test \"client\" model * @param body client model (required) * @return Client */ @@ -98,7 +98,7 @@ public interface FakeApi { /** * To test enum parameters * Sync method - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -113,7 +113,7 @@ public interface FakeApi { @retrofit.http.FormUrlEncoded @GET("/fake") Void testEnumParameters( - @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble + @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble ); /** @@ -134,6 +134,6 @@ public interface FakeApi { @retrofit.http.FormUrlEncoded @GET("/fake") void testEnumParameters( - @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble, Callback cb + @retrofit.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit.http.Field("enum_form_string") String enumFormString, @retrofit.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit.http.Header("enum_header_string") String enumHeaderString, @retrofit.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit.http.Query("enum_query_string") String enumQueryString, @retrofit.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit.http.Field("enum_query_double") Double enumQueryDouble, Callback cb ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java index 4bca9018689..287c083b188 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/FormatTest.java @@ -72,8 +72,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -92,8 +92,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/retrofit2-play24/pom.xml b/samples/client/petstore/java/retrofit2-play24/pom.xml index a6cb9f52121..efbba49f5c1 100644 --- a/samples/client/petstore/java/retrofit2-play24/pom.xml +++ b/samples/client/petstore/java/retrofit2-play24/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java index 332e1f4e224..b75cd316ac1 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/Pair.java @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java index 999ca1fd386..339a3fb36d5 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/StringUtil.java @@ -13,7 +13,7 @@ package io.swagger.client; -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index c5b84a1b8fd..4ac36d98590 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -21,7 +21,7 @@ import java.util.List; /** * Holds ApiKey auth info */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index 909c30a1b03..d64d61f3c52 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * AdditionalPropertiesClass */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class AdditionalPropertiesClass { @JsonProperty("map_property") private Map mapProperty = new HashMap(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java index ab1400635b3..a1e8586074f 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java @@ -25,7 +25,7 @@ import javax.validation.constraints.*; /** * Animal */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00")@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) @JsonSubTypes({ @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), }) diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java index 6529f902150..21032adf0b1 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -22,7 +22,7 @@ import javax.validation.constraints.*; /** * AnimalFarm */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class AnimalFarm extends ArrayList { @Override diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index f0eaa2635f0..2e8235c8c49 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ArrayOfArrayOfNumberOnly { @JsonProperty("ArrayArrayNumber") private List> arrayArrayNumber = new ArrayList>(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 4e76d18065b..4d909396195 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayOfNumberOnly */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ArrayOfNumberOnly { @JsonProperty("ArrayNumber") private List arrayNumber = new ArrayList(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java index 7b6dda6f0e8..29b73261642 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ArrayTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * ArrayTest */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ArrayTest { @JsonProperty("array_of_string") private List arrayOfString = new ArrayList(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java index 86a61a22cda..a04574c0ea9 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Cat.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Cat */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Cat extends Animal { @JsonProperty("declawed") private Boolean declawed = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java index 9a8c766c6c0..c8691c3ee4f 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Category.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Category */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Category { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java index 81efcdee6ca..5fe97c0b21c 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ClassModel.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model with \"_class\" property */ @ApiModel(description = "Model for testing model with \"_class\" property") -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ClassModel { @JsonProperty("_class") private String propertyClass = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java index 489af709c19..f2f6c4b6130 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Client.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Client */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Client { @JsonProperty("client") private String client = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java index c3e700c72fb..9e18aa16b51 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Dog.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Dog */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Dog extends Animal { @JsonProperty("breed") private String breed = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java index 116c874f765..973534c6c1d 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumArrays.java @@ -25,7 +25,7 @@ import javax.validation.constraints.*; /** * EnumArrays */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class EnumArrays { /** * Gets or Sets justSymbol diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java index d14bf8cc76e..f0da7fb482c 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * EnumTest */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class EnumTest { /** * Gets or Sets enumString diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java index a249c4b5b96..8f20e7c3ae5 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * FormatTest */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class FormatTest { @JsonProperty("integer") private Integer integer = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java index 3ee7b857530..6a96f1964a0 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/HasOnlyReadOnly.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * HasOnlyReadOnly */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class HasOnlyReadOnly { @JsonProperty("bar") private String bar = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java index ff9e95d36a8..4db64f866f5 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MapTest.java @@ -26,7 +26,7 @@ import javax.validation.constraints.*; /** * MapTest */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class MapTest { @JsonProperty("map_map_of_string") private Map> mapMapOfString = new HashMap>(); diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 84f3bf1791a..536edaea064 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -28,7 +28,7 @@ import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") private String uuid = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java index 1c7e6e4ae71..8142243744e 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Model200Response.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model name starting with number */ @ApiModel(description = "Model for testing model name starting with number") -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Model200Response { @JsonProperty("name") private Integer name = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java index e37ed10f305..0fdfa8f52f7 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelApiResponse.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * ModelApiResponse */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ModelApiResponse { @JsonProperty("code") private Integer code = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java index b50a1f7338c..1e4ae4973d3 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ModelReturn.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing reserved words */ @ApiModel(description = "Model for testing reserved words") -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ModelReturn { @JsonProperty("return") private Integer _return = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java index 7b44370f3d2..872603a2329 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Name.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; * Model for testing model name same as property name */ @ApiModel(description = "Model for testing model name same as property name") -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Name { @JsonProperty("name") private Integer name = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java index e48dbe99417..06fdd444d86 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/NumberOnly.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * NumberOnly */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class NumberOnly { @JsonProperty("JustNumber") private BigDecimal justNumber = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java index dcb7f9264f3..6f0be730175 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Order.java @@ -24,7 +24,7 @@ import javax.validation.constraints.*; /** * Order */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Order { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java index 7bc5658cef7..0bb51a4f5c0 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Pet.java @@ -27,7 +27,7 @@ import javax.validation.constraints.*; /** * Pet */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Pet { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java index 349de2635ad..7b9247bb24e 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/ReadOnlyFirst.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * ReadOnlyFirst */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class ReadOnlyFirst { @JsonProperty("bar") private String bar = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java index a5a05393b4a..480fb41e9ea 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/SpecialModelName.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * SpecialModelName */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class SpecialModelName { @JsonProperty("$special[property.name]") private Long specialPropertyName = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java index da3d48cc49f..271c21de570 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Tag.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * Tag */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class Tag { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java index d0143c1e4aa..dfec21c2a96 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/User.java @@ -23,7 +23,7 @@ import javax.validation.constraints.*; /** * User */ -@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2016-12-14T17:41:48.242+08:00") + public class User { @JsonProperty("id") private Long id = null; diff --git a/samples/client/petstore/java/retrofit2/docs/FakeApi.md b/samples/client/petstore/java/retrofit2/docs/FakeApi.md index 4cdd34df763..d1f45eda4d4 100644 --- a/samples/client/petstore/java/retrofit2/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -138,6 +140,8 @@ Name | Type | Description | Notes To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -152,7 +156,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -173,7 +177,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 247b281c33b..ec8d6f869c9 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + @@ -134,6 +142,7 @@ joda-time ${jodatime-version} + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java index 789f2ebbe00..94820a21964 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/FakeApi.java @@ -18,10 +18,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Call<Client> */ @@ -62,7 +63,7 @@ public interface FakeApi { /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -77,7 +78,7 @@ public interface FakeApi { @retrofit2.http.FormUrlEncoded @GET("fake") Call testEnumParameters( - @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } 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 index d3f6a48e365..21572a18938 100644 --- 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 @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface PetApi { /** * Add a new pet to the store 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 index f9df7d8e8d6..643a7302b84 100644 --- 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 @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface StoreApi { /** * Delete purchase order by ID 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 index ee1114dc2dc..87a4921c70e 100644 --- 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 @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface UserApi { /** * Create user diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java index 4bca9018689..287c083b188 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/FormatTest.java @@ -72,8 +72,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -92,8 +92,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") diff --git a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md index 4cdd34df763..d1f45eda4d4 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md +++ b/samples/client/petstore/java/retrofit2rx/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```java // Import classes: @@ -138,6 +140,8 @@ Name | Type | Description | Notes To test enum parameters +To test enum parameters + ### Example ```java // Import classes: @@ -152,7 +156,7 @@ List enumHeaderStringArray = Arrays.asList("enumHeaderStringArray_exampl String enumHeaderString = "-efg"; // String | Header parameter enum test (string) List enumQueryStringArray = Arrays.asList("enumQueryStringArray_example"); // List | Query parameter enum test (string array) String enumQueryString = "-efg"; // String | Query parameter enum test (string) -BigDecimal enumQueryInteger = new BigDecimal(); // BigDecimal | Query parameter enum test (double) +Integer enumQueryInteger = 56; // Integer | Query parameter enum test (double) Double enumQueryDouble = 3.4D; // Double | Query parameter enum test (double) try { Void result = apiInstance.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); @@ -173,7 +177,7 @@ Name | Type | Description | Notes **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] - **enumQueryInteger** | **BigDecimal**| Query parameter enum test (double) | [optional] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index ccc4b12d82b..bd7e080ae39 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + @@ -144,6 +152,7 @@ adapter-rxjava ${retrofit-version} + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java index a6772ec6f93..41b5a883596 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/FakeApi.java @@ -18,10 +18,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface FakeApi { /** * To test \"client\" model - * + * To test \"client\" model * @param body client model (required) * @return Call<Client> */ @@ -62,7 +63,7 @@ public interface FakeApi { /** * To test enum parameters - * + * To test enum parameters * @param enumFormStringArray Form parameter enum test (string array) (optional) * @param enumFormString Form parameter enum test (string) (optional, default to -efg) * @param enumHeaderStringArray Header parameter enum test (string array) (optional) @@ -77,7 +78,7 @@ public interface FakeApi { @retrofit2.http.FormUrlEncoded @GET("fake") Observable testEnumParameters( - @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") BigDecimal enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble + @retrofit2.http.Field("enum_form_string_array") List enumFormStringArray, @retrofit2.http.Field("enum_form_string") String enumFormString, @retrofit2.http.Header("enum_header_string_array") List enumHeaderStringArray, @retrofit2.http.Header("enum_header_string") String enumHeaderString, @retrofit2.http.Query("enum_query_string_array") CSVParams enumQueryStringArray, @retrofit2.http.Query("enum_query_string") String enumQueryString, @retrofit2.http.Query("enum_query_integer") Integer enumQueryInteger, @retrofit2.http.Field("enum_query_double") Double enumQueryDouble ); } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index e05fd538d9e..e7ee14b2c0e 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -17,6 +17,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface PetApi { /** * Add a new pet to the store diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index e8eac3c525b..eab5f872d0b 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface StoreApi { /** * Delete purchase order by ID diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java index 579134971f8..af1bb5f0ffd 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/UserApi.java @@ -15,6 +15,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public interface UserApi { /** * Create user diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java index 12351021cfe..af905454860 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/AnimalFarm.java @@ -32,7 +32,7 @@ public class AnimalFarm extends ArrayList { if (o == null || getClass() != o.getClass()) { return false; } - return true; + return super.equals(o); } @Override diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java index 4bca9018689..287c083b188 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/FormatTest.java @@ -72,8 +72,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(example = "null", value = "") @@ -92,8 +92,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(example = "null", value = "") From 218d1060145db1a63bc2750776cef6370d5426fc Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 15 Dec 2016 22:08:40 +0800 Subject: [PATCH 177/269] list all supported clients/frameworks/doc --- README.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3fccbaff1f0..fe062cb4e1c 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,12 @@ :warning: If the OpenAPI/Swagger spec is obtained from an untrusted source, please make sure you've reviewed the spec before using Swagger Codegen to generate the API client, server stub or documentation as [code injection](https://en.wikipedia.org/wiki/Code_injection) may occur :warning: ## Overview -This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). +This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: + +- **API clients**: ActionScript, C# (.net 2.0, 4.0 or later) , C++ (cpprest, Qt5, Tizen), Clojure, Dart, Go, Groovy, Haskell, Java (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), Node.js (ES5, ES6, AngularJS with Google Closure Compiler annotations) Objective-C, Perl, PHP, Python, Ruby, Scala, Swift (2.x, 3.x), Typescript (Angular1.x, Angular2.x, Fetch, Node) +- **Server stubs**: C# (ASP.NET Core, NancyFx), Erlang, Go, Haskell, Java (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), PHP (Lumen, Slim, Silex), Python Flask, NodeJS, Ruby (Sinatra, Rails5), Scala (Scalatra) +- **API documentations**: HTML, Confluence Wiki +- **Others**: JMeter Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project. From 733cdb08f0397bfa1525d6d000a1aa12126bef5f Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 15 Dec 2016 22:18:09 +0800 Subject: [PATCH 178/269] formatting for list of api clients/servers --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index fe062cb4e1c..1e7f4fd9d15 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,10 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: ActionScript, C# (.net 2.0, 4.0 or later) , C++ (cpprest, Qt5, Tizen), Clojure, Dart, Go, Groovy, Haskell, Java (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), Node.js (ES5, ES6, AngularJS with Google Closure Compiler annotations) Objective-C, Perl, PHP, Python, Ruby, Scala, Swift (2.x, 3.x), Typescript (Angular1.x, Angular2.x, Fetch, Node) -- **Server stubs**: C# (ASP.NET Core, NancyFx), Erlang, Go, Haskell, Java (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), PHP (Lumen, Slim, Silex), Python Flask, NodeJS, Ruby (Sinatra, Rails5), Scala (Scalatra) -- **API documentations**: HTML, Confluence Wiki -- **Others**: JMeter +- **API clients**: **ActionScript**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) +- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) +- **API documentations**: **HTML**, **Confluence Wiki** +- **Others**: **JMeter** Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project. From 91af8066cdee6bbf0ac72be9f2be27aa9eae1169 Mon Sep 17 00:00:00 2001 From: Yohana Khoury Date: Fri, 16 Dec 2016 05:56:38 +0200 Subject: [PATCH 179/269] boolean values from JSON are treated as strings (#4229) * Change the value types in additionalProperties and dynamicProperties to Object instead of String. Change methods that insert values to these maps to use Object as the type of the value instead of String. * Fix run-all-petstore run: use toString instead of casting --- .../codegen/config/CodegenConfigurator.java | 14 +++++++------- .../languages/AbstractTypeScriptClientCodegen.java | 2 +- .../codegen/config/CodegenConfiguratorTest.java | 12 ++++++++++-- 3 files changed, 18 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 1dd1ced4d74..6ac586af8f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -57,7 +57,7 @@ public class CodegenConfigurator { private Map systemProperties = new HashMap(); private Map instantiationTypes = new HashMap(); private Map typeMappings = new HashMap(); - private Map additionalProperties = new HashMap(); + private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); private String gitUserId="GIT_USER_ID"; @@ -65,7 +65,7 @@ public class CodegenConfigurator { private String releaseNote="Minor update"; private String httpUserAgent; - private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values + private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values public CodegenConfigurator() { this.setOutputDir("."); @@ -255,16 +255,16 @@ public class CodegenConfigurator { return this; } - public Map getAdditionalProperties() { + public Map getAdditionalProperties() { return additionalProperties; } - public CodegenConfigurator setAdditionalProperties(Map additionalProperties) { + public CodegenConfigurator setAdditionalProperties(Map additionalProperties) { this.additionalProperties = additionalProperties; return this; } - public CodegenConfigurator addAdditionalProperty(String key, String value) { + public CodegenConfigurator addAdditionalProperty(String key, Object value) { this.additionalProperties.put(key, value); return this; } @@ -398,12 +398,12 @@ public class CodegenConfigurator { @JsonAnySetter public CodegenConfigurator addDynamicProperty(String name, Object value) { - dynamicProperties.put(name, value.toString()); + dynamicProperties.put(name, value); return this; } @JsonAnyGetter - public Map getDynamicProperties() { + public Map getDynamicProperties() { return dynamicProperties; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index e1b05af4ebb..2fccf1061cf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -103,7 +103,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } if (additionalProperties.containsKey(CodegenConstants.SUPPORTS_ES6)) { - setSupportsES6(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SUPPORTS_ES6))); + setSupportsES6(Boolean.valueOf(additionalProperties.get(CodegenConstants.SUPPORTS_ES6).toString())); additionalProperties.put("supportsES6", getSupportsES6()); } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java index 6f39eb1af99..e3de3fdf8af 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java @@ -156,12 +156,16 @@ public class CodegenConfiguratorTest { public void testAdditionalProperties() throws Exception { configurator.addAdditionalProperty("foo", "bar") - .addAdditionalProperty("hello", "world"); + .addAdditionalProperty("hello", "world") + .addAdditionalProperty("supportJava6", false) + .addAdditionalProperty("useRxJava", true); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); assertValueInMap(clientOptInput.getConfig().additionalProperties(), "foo", "bar"); assertValueInMap(clientOptInput.getConfig().additionalProperties(), "hello", "world"); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "supportJava6", false); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "useRxJava", true); } @Test @@ -241,10 +245,14 @@ public class CodegenConfiguratorTest { @Test public void testDynamicProperties() throws Exception { configurator.addDynamicProperty(CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + configurator.addDynamicProperty("supportJava6", false); + configurator.addDynamicProperty("useRxJava", true); final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "supportJava6", false); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "useRxJava", true); } @Test @@ -344,7 +352,7 @@ public class CodegenConfiguratorTest { }}; } - private static void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { + private static void assertValueInMap(Map map, String propertyKey, Object expectedPropertyValue) { assertTrue(map.containsKey(propertyKey)); assertEquals(map.get(propertyKey), expectedPropertyValue); } From 6ade00166397226d63da63884b86456622d7bce9 Mon Sep 17 00:00:00 2001 From: Christoph Keller Date: Fri, 16 Dec 2016 05:08:24 +0100 Subject: [PATCH 180/269] CodegenResponse.isListContainer is false for array types. (#4400) CodegenResponse's isListContainer property is always false for "array" types. Don't know where the check for "list" comes from but in CodegenOperation, there's a check for "list" and "array". No mustache file makes use of isListContainer inside responses yet, so should not change any existing behavior. --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 2954a70845b..1e3cc438126 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2208,7 +2208,7 @@ public class DefaultCodegen { r.simpleType = false; r.containerType = cm.containerType; r.isMapContainer = "map".equals(cm.containerType); - r.isListContainer = "list".equals(cm.containerType); + r.isListContainer = "list".equalsIgnoreCase(cm.containerType) || "array".equalsIgnoreCase(cm.containerType); } else { r.simpleType = true; } From bd81f3264d0d849d1e233121986c782248c90aa4 Mon Sep 17 00:00:00 2001 From: Brian Shamblen Date: Fri, 16 Dec 2016 02:06:28 -0800 Subject: [PATCH 181/269] [html2] Fix import statements for most languages (#4243) * [html2] Clean up namespace issues in code samples * pull c# and php package namespace from --additional-properties arg phpInvokerPackage arg now sets the PHP namespace and packageName sets the CSharp namespace. invokerPackage still works for Java and Android namespace. --- .../io/swagger/codegen/CodegenConstants.java | 3 + .../languages/StaticHtml2Generator.java | 35 +- .../main/resources/htmlDocs2/index.mustache | 28 +- .../htmlDocs2/sample_android.mustache | 4 +- .../htmlDocs2/sample_csharp.mustache | 6 +- .../resources/htmlDocs2/sample_java.mustache | 4 +- .../resources/htmlDocs2/sample_js.mustache | 6 +- .../resources/htmlDocs2/sample_objc.mustache | 1 - .../resources/htmlDocs2/sample_php.mustache | 15 +- samples/html2/index.html | 1160 ++++++----------- 10 files changed, 461 insertions(+), 801 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 84c5c9e8714..094ff38e8fd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -16,6 +16,9 @@ public class CodegenConstants { public static final String INVOKER_PACKAGE = "invokerPackage"; public static final String INVOKER_PACKAGE_DESC = "root package for generated code"; + public static final String PHP_INVOKER_PACKAGE = "phpInvokerPackage"; + public static final String PHP_INVOKER_PACKAGE_DESC = "root package for generated php code"; + public static final String GROUP_ID = "groupId"; public static final String GROUP_ID_DESC = "groupId in generated pom.xml"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 2907c1dfc43..7a07ef8a58f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -7,17 +7,23 @@ import io.swagger.models.Swagger; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.Info; +import org.apache.commons.lang3.StringUtils; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; + protected String invokerPackage = "io.swagger.client"; // default for Java and Android + protected String phpInvokerPackage = "Swagger\\Client"; // default for PHP + protected String packageName = "IO.Swagger"; // default for C# protected String groupId = "io.swagger"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; + protected String jsProjectName; + protected String jsModuleName; public StaticHtml2Generator() { super(); @@ -33,6 +39,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi cliOptions.add(new CliOption("licenseInfo", "a short description of the license")); cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); @@ -44,6 +52,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi additionalProperties.put("licenseInfo", "All rights reserved"); additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.PHP_INVOKER_PACKAGE, phpInvokerPackage); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); @@ -101,6 +111,29 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi return objs; } + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (StringUtils.isBlank(jsProjectName) && info.getTitle() != null) { + // when jsProjectName is not specified, generate it from info.title + jsProjectName = sanitizeName(dashize(info.getTitle())); + } + } + + // default values + if (StringUtils.isBlank(jsProjectName)) { + jsProjectName = "swagger-js-client"; + } + if (StringUtils.isBlank(jsModuleName)) { + jsModuleName = camelize(underscore(jsProjectName)); + } + + additionalProperties.put("jsProjectName", jsProjectName); + additionalProperties.put("jsModuleName", jsModuleName); + } @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index e7dbd535258..3f5cb05b3dc 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -222,50 +222,36 @@
    -
    
    -  curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    -  
    +
    curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    -
    
    -  {{>sample_java}}
    -                            
    +
    {{>sample_java}}
    -
    
    -  {{>sample_android}}
    -                            
    +
    {{>sample_android}}
    -
    
    -  {{>sample_objc}}
    -                              
    +
    {{>sample_objc}}
    -
    
    -  {{>sample_js}}
    -                              
    +
    {{>sample_js}}
    -
    
    -  {{>sample_csharp}}
    -                              
    +
    {{>sample_csharp}}
    -
    
    -  {{>sample_php}}
    -                              
    +
    {{>sample_php}}
    diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache index cb23590bf53..2bf0769666c 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache @@ -1,4 +1,4 @@ -import {{{package}}}.{{{classname}}}; +import {{{invokerPackage}}}.api.{{{classname}}}; public class {{{classname}}}Example { @@ -15,4 +15,4 @@ public class {{{classname}}}Example { e.printStackTrace(); } } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache index fd7a75d0da2..ebfef12699f 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache @@ -2,9 +2,7 @@ using System; using System.Diagnostics; using {{packageName}}.Api; using {{packageName}}.Client; -{{#modelPackage}} -using {{{.}}}; -{{/modelPackage}} +using {{packageName}}.Model; namespace Example { @@ -48,4 +46,4 @@ namespace Example } } } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache index 160916ed81f..02454e6cc7d 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache @@ -1,7 +1,7 @@ import {{{invokerPackage}}}.*; import {{{invokerPackage}}}.auth.*; import {{{invokerPackage}}}.model.*; -import {{{package}}}.{{{classname}}}; +import {{{invokerPackage}}}.api.{{{classname}}}; import java.io.File; import java.util.*; @@ -38,4 +38,4 @@ public class {{{classname}}}Example { e.printStackTrace(); } } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache index 8c77656a1a6..4fc35f07711 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache @@ -1,6 +1,6 @@ -var {{{moduleName}}} = require('{{{projectName}}}'); +var {{{jsModuleName}}} = require('{{{jsProjectName}}}'); {{#hasAuthMethods}} -var defaultClient = {{{moduleName}}}.ApiClient.instance; +var defaultClient = {{{jsModuleName}}}.ApiClient.instance; {{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} var {{{name}}} = defaultClient.authentications['{{{name}}}']; @@ -17,7 +17,7 @@ var {{{name}}} = defaultClient.authentications['{{{name}}}']; {{/authMethods}} {{/hasAuthMethods}} -var api = new {{{moduleName}}}.{{{classname}}}(){{#hasParams}} +var api = new {{{jsModuleName}}}.{{{classname}}}(){{#hasParams}} {{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} {{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache index 88aa2b08b74..232bf0c2f05 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache @@ -13,7 +13,6 @@ [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; {{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} - {{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache index 4b9ee43b866..b479530d6ca 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache @@ -1,18 +1,18 @@ - +<?php require_once(__DIR__ . '/vendor/autoload.php'); {{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} // Configure HTTP basic authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME'); -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} +{{phpInvokerPackage}}\Configuration::getDefaultConfiguration()->setUsername('YOUR_USERNAME'); +{{phpInvokerPackage}}\Configuration::getDefaultConfiguration()->setPassword('YOUR_PASSWORD');{{/isBasic}}{{#isApiKey}} // Configure API key authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); +{{phpInvokerPackage}}\Configuration::getDefaultConfiguration()->setApiKey('{{{keyParamName}}}', 'YOUR_API_KEY'); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -// {{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} +// {{phpInvokerPackage}}\Configuration::getDefaultConfiguration()->setApiKeyPrefix('{{{keyParamName}}}', 'Bearer');{{/isApiKey}}{{#isOAuth}} // Configure OAuth2 access token for authorization: {{{name}}} -{{{invokerPackage}}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} +{{phpInvokerPackage}}\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');{{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} -$api_instance = new {{invokerPackage}}\Api\{{classname}}(); +$api_instance = new Swagger\Client\Api\{{classname}}(); {{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} {{/allParams}} @@ -22,3 +22,4 @@ try { } catch (Exception $e) { echo 'Exception when calling {{classname}}->{{operationId}}: ', $e->getMessage(), PHP_EOL; } +?> \ No newline at end of file diff --git a/samples/html2/index.html b/samples/html2/index.html index d7ee2cea468..1cc445b3f32 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -1010,16 +1010,13 @@ margin-bottom: 20px;
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/pet"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/pet"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -1042,14 +1039,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -1063,22 +1057,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     Pet *body = ; // Pet object that needs to be added to the store
     
     PetApi *apiInstance = [[PetApi alloc] init];
    @@ -1090,20 +1080,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var body = ; // {Pet} Pet object that needs to be added to the store
     
    @@ -1116,20 +1104,18 @@ var callback = function(error, data, response) {
       }
     };
     api.addPet(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -1155,20 +1141,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $body = ; // Pet | Pet object that needs to be added to the store
     
     try {
    @@ -1176,8 +1159,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->addPet: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -1275,16 +1257,13 @@ try {
    -
    
    -  curl -X delete "http://petstore.swagger.io/v2/pet/{petId}"
    -  
    +
    curl -X delete "http://petstore.swagger.io/v2/pet/{petId}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -1308,14 +1287,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -1330,22 +1306,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     Long *petId = 789; // Pet id to delete
     String *apiKey = apiKey_example; //  (optional)
     
    @@ -1359,20 +1331,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var petId = 789; // {Long} Pet id to delete
     
    @@ -1388,20 +1358,18 @@ var callback = function(error, data, response) {
       }
     };
     api.deletePet(petId, opts, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -1428,20 +1396,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $petId = 789; // Long | Pet id to delete
     $apiKey = apiKey_example; // String | 
     
    @@ -1450,8 +1415,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->deletePet: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -1578,16 +1542,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/pet/findByStatus?status="
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -1611,14 +1572,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -1633,22 +1591,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     array[String] *status = ; // Status values that need to be considered for filter
     
     PetApi *apiInstance = [[PetApi alloc] init];
    @@ -1663,20 +1617,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var status = ; // {array[String]} Status values that need to be considered for filter
     
    @@ -1689,20 +1641,18 @@ var callback = function(error, data, response) {
       }
     };
     api.findPetsByStatus(status, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -1729,20 +1679,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $status = ; // array[String] | Status values that need to be considered for filter
     
     try {
    @@ -1751,8 +1698,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->findPetsByStatus: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -1890,16 +1836,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/pet/findByTags?tags="
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -1923,14 +1866,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -1945,22 +1885,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     array[String] *tags = ; // Tags to filter by
     
     PetApi *apiInstance = [[PetApi alloc] init];
    @@ -1975,20 +1911,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var tags = ; // {array[String]} Tags to filter by
     
    @@ -2001,20 +1935,18 @@ var callback = function(error, data, response) {
       }
     };
     api.findPetsByTags(tags, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -2041,20 +1973,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $tags = ; // array[String] | Tags to filter by
     
     try {
    @@ -2063,8 +1992,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->findPetsByTags: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -2200,16 +2128,13 @@ try {
    -
    
    -  curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    -  
    +
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -2235,14 +2160,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -2257,24 +2179,20 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure API key authorization: (authentication scheme: api_key)
     [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
     // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
     //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
     
    -
     Long *petId = 789; // ID of pet to return
     
     PetApi *apiInstance = [[PetApi alloc] init];
    @@ -2289,14 +2207,12 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure API key authorization: api_key
     var api_key = defaultClient.authentications['api_key'];
    @@ -2304,7 +2220,7 @@ api_key.apiKey = "YOUR API KEY"
     // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
     //api_key.apiKeyPrefix['api_key'] = "Token"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var petId = 789; // {Long} ID of pet to return
     
    @@ -2317,20 +2233,18 @@ var callback = function(error, data, response) {
       }
     };
     api.getPetById(petId, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -2359,22 +2273,19 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure API key authorization: api_key
    -io.swagger.client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
     // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    -// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
    +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $petId = 789; // Long | ID of pet to return
     
     try {
    @@ -2383,8 +2294,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->getPetById: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -2516,16 +2426,13 @@ try {
    -
    
    -  curl -X put "http://petstore.swagger.io/v2/pet"
    -  
    +
    curl -X put "http://petstore.swagger.io/v2/pet"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -2548,14 +2455,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -2569,22 +2473,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     Pet *body = ; // Pet object that needs to be added to the store
     
     PetApi *apiInstance = [[PetApi alloc] init];
    @@ -2596,20 +2496,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var body = ; // {Pet} Pet object that needs to be added to the store
     
    @@ -2622,20 +2520,18 @@ var callback = function(error, data, response) {
       }
     };
     api.updatePet(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -2661,20 +2557,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $body = ; // Pet | Pet object that needs to be added to the store
     
     try {
    @@ -2682,8 +2575,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->updatePet: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -2785,16 +2677,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/pet/{petId}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -2819,14 +2708,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -2842,22 +2728,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     Long *petId = 789; // ID of pet that needs to be updated
     String *name = name_example; // Updated name of the pet (optional)
     String *status = status_example; // Updated status of the pet (optional)
    @@ -2873,20 +2755,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var petId = 789; // {Long} ID of pet that needs to be updated
     
    @@ -2903,20 +2783,18 @@ var callback = function(error, data, response) {
       }
     };
     api.updatePetWithForm(petId, opts, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -2944,20 +2822,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $petId = 789; // Long | ID of pet that needs to be updated
     $name = name_example; // String | Updated name of the pet
     $status = status_example; // String | Updated status of the pet
    @@ -2967,8 +2842,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->updatePetWithForm: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -3129,16 +3003,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/pet/{petId}/uploadImage"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .PetApi;
    +import io.swagger.client.api.PetApi;
     
     import java.io.File;
     import java.util.*;
    @@ -3164,14 +3035,11 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .PetApi;
    +                            
    import io.swagger.client.api.PetApi;
     
     public class PetApiExample {
     
    @@ -3188,22 +3056,18 @@ public class PetApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
     [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
     
    -
     Long *petId = 789; // ID of pet to update
     String *additionalMetadata = additionalMetadata_example; // Additional data to pass to server (optional)
     file *file = /path/to/file.txt; // file to upload (optional)
    @@ -3222,20 +3086,18 @@ PetApi *apiInstance = [[PetApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure OAuth2 access token for authorization: petstore_auth
     var petstore_auth = defaultClient.authentications['petstore_auth'];
     petstore_auth.accessToken = "YOUR ACCESS TOKEN"
     
    -var api = new .PetApi()
    +var api = new SwaggerPetstore.PetApi()
     
     var petId = 789; // {Long} ID of pet to update
     
    @@ -3252,20 +3114,18 @@ var callback = function(error, data, response) {
       }
     };
     api.uploadFile(petId, opts, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -3294,20 +3154,17 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure OAuth2 access token for authorization: petstore_auth
    -io.swagger.client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_ACCESS_TOKEN');
     
    -$api_instance = new io.swagger.client\Api\PetApi();
    +$api_instance = new Swagger\Client\Api\PetApi();
     $petId = 789; // Long | ID of pet to update
     $additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server
     $file = /path/to/file.txt; // file | file to upload
    @@ -3318,8 +3175,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling PetApi->uploadFile: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -3523,16 +3379,13 @@ try {
    -
    
    -  curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
    -  
    +
    curl -X delete "http://petstore.swagger.io/v2/store/order/{orderId}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .StoreApi;
    +import io.swagger.client.api.StoreApi;
     
     import java.io.File;
     import java.util.*;
    @@ -3550,14 +3403,11 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .StoreApi;
    +                            
    import io.swagger.client.api.StoreApi;
     
     public class StoreApiExample {
     
    @@ -3571,18 +3421,14 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -String *orderId = orderId_example; // ID of the order that needs to be deleted
    +                              
    String *orderId = orderId_example; // ID of the order that needs to be deleted
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
     
    @@ -3593,15 +3439,13 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .StoreApi()
    +var api = new SwaggerPetstore.StoreApi()
     
     var orderId = orderId_example; // {String} ID of the order that needs to be deleted
     
    @@ -3614,20 +3458,18 @@ var callback = function(error, data, response) {
       }
     };
     api.deleteOrder(orderId, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -3650,17 +3492,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\StoreApi();
    +$api_instance = new Swagger\Client\Api\StoreApi();
     $orderId = orderId_example; // String | ID of the order that needs to be deleted
     
     try {
    @@ -3668,8 +3507,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling StoreApi->deleteOrder: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -3759,16 +3597,13 @@ try {
    -
    
    -  curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    -  
    +
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .StoreApi;
    +import io.swagger.client.api.StoreApi;
     
     import java.io.File;
     import java.util.*;
    @@ -3793,14 +3628,11 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .StoreApi;
    +                            
    import io.swagger.client.api.StoreApi;
     
     public class StoreApiExample {
     
    @@ -3814,17 +3646,14 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  Configuration *apiConfig = [Configuration sharedConfig];
    +                              
    Configuration *apiConfig = [Configuration sharedConfig];
     
     // Configure API key authorization: (authentication scheme: api_key)
     [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"];
    @@ -3832,7 +3661,6 @@ public class StoreApiExample {
     //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"];
     
     
    -
     StoreApi *apiInstance = [[StoreApi alloc] init];
     
     // Returns pet inventories by status
    @@ -3845,14 +3673,12 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    -var defaultClient = .ApiClient.instance;
    +                              
    var SwaggerPetstore = require('swagger_petstore');
    +var defaultClient = SwaggerPetstore.ApiClient.instance;
     
     // Configure API key authorization: api_key
     var api_key = defaultClient.authentications['api_key'];
    @@ -3860,7 +3686,7 @@ api_key.apiKey = "YOUR API KEY"
     // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
     //api_key.apiKeyPrefix['api_key'] = "Token"
     
    -var api = new .StoreApi()
    +var api = new SwaggerPetstore.StoreApi()
     
     var callback = function(error, data, response) {
       if (error) {
    @@ -3870,20 +3696,18 @@ var callback = function(error, data, response) {
       }
     };
     api.getInventory(callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -3911,22 +3735,19 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
     // Configure API key authorization: api_key
    -io.swagger.client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
    +Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('api_key', 'YOUR_API_KEY');
     // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    -// io.swagger.client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
    +// Swagger\Client\Configuration::getDefaultConfiguration()->setApiKeyPrefix('api_key', 'Bearer');
     
    -$api_instance = new io.swagger.client\Api\StoreApi();
    +$api_instance = new Swagger\Client\Api\StoreApi();
     
     try {
         $result = $api_instance->getInventory();
    @@ -3934,8 +3755,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling StoreApi->getInventory: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -4026,16 +3846,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/store/order/{orderId}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .StoreApi;
    +import io.swagger.client.api.StoreApi;
     
     import java.io.File;
     import java.util.*;
    @@ -4054,14 +3871,11 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .StoreApi;
    +                            
    import io.swagger.client.api.StoreApi;
     
     public class StoreApiExample {
     
    @@ -4076,18 +3890,14 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -Long *orderId = 789; // ID of pet that needs to be fetched
    +                              
    Long *orderId = 789; // ID of pet that needs to be fetched
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
     
    @@ -4101,15 +3911,13 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .StoreApi()
    +var api = new SwaggerPetstore.StoreApi()
     
     var orderId = 789; // {Long} ID of pet that needs to be fetched
     
    @@ -4122,20 +3930,18 @@ var callback = function(error, data, response) {
       }
     };
     api.getOrderById(orderId, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -4159,17 +3965,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\StoreApi();
    +$api_instance = new Swagger\Client\Api\StoreApi();
     $orderId = 789; // Long | ID of pet that needs to be fetched
     
     try {
    @@ -4178,8 +3981,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling StoreApi->getOrderById: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -4313,16 +4115,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/store/order"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/store/order"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .StoreApi;
    +import io.swagger.client.api.StoreApi;
     
     import java.io.File;
     import java.util.*;
    @@ -4341,14 +4140,11 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .StoreApi;
    +                            
    import io.swagger.client.api.StoreApi;
     
     public class StoreApiExample {
     
    @@ -4363,18 +4159,14 @@ public class StoreApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -Order *body = ; // order placed for purchasing the pet
    +                              
    Order *body = ; // order placed for purchasing the pet
     
     StoreApi *apiInstance = [[StoreApi alloc] init];
     
    @@ -4388,15 +4180,13 @@ StoreApi *apiInstance = [[StoreApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .StoreApi()
    +var api = new SwaggerPetstore.StoreApi()
     
     var body = ; // {Order} order placed for purchasing the pet
     
    @@ -4409,20 +4199,18 @@ var callback = function(error, data, response) {
       }
     };
     api.placeOrder(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -4446,17 +4234,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\StoreApi();
    +$api_instance = new Swagger\Client\Api\StoreApi();
     $body = ; // Order | order placed for purchasing the pet
     
     try {
    @@ -4465,8 +4250,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling StoreApi->placeOrder: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -4609,16 +4393,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/user"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/user"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -4636,14 +4417,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -4657,18 +4435,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -User *body = ; // Created user object
    +                              
    User *body = ; // Created user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -4679,15 +4453,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var body = ; // {User} Created user object
     
    @@ -4700,20 +4472,18 @@ var callback = function(error, data, response) {
       }
     };
     api.createUser(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -4736,17 +4506,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $body = ; // User | Created user object
     
     try {
    @@ -4754,8 +4521,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->createUser: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -4853,16 +4619,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/user/createWithArray"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -4880,14 +4643,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -4901,18 +4661,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -array[User] *body = ; // List of user object
    +                              
    array[User] *body = ; // List of user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -4923,15 +4679,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var body = ; // {array[User]} List of user object
     
    @@ -4944,20 +4698,18 @@ var callback = function(error, data, response) {
       }
     };
     api.createUsersWithArrayInput(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -4980,17 +4732,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $body = ; // array[User] | List of user object
     
     try {
    @@ -4998,8 +4747,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->createUsersWithArrayInput: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -5100,16 +4848,13 @@ try {
    -
    
    -  curl -X post "http://petstore.swagger.io/v2/user/createWithList"
    -  
    +
    curl -X post "http://petstore.swagger.io/v2/user/createWithList"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -5127,14 +4872,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -5148,18 +4890,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -array[User] *body = ; // List of user object
    +                              
    array[User] *body = ; // List of user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -5170,15 +4908,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var body = ; // {array[User]} List of user object
     
    @@ -5191,20 +4927,18 @@ var callback = function(error, data, response) {
       }
     };
     api.createUsersWithListInput(body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -5227,17 +4961,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $body = ; // array[User] | List of user object
     
     try {
    @@ -5245,8 +4976,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->createUsersWithListInput: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -5347,16 +5077,13 @@ try {
    -
    
    -  curl -X delete "http://petstore.swagger.io/v2/user/{username}"
    -  
    +
    curl -X delete "http://petstore.swagger.io/v2/user/{username}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -5374,14 +5101,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -5395,18 +5119,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -String *username = username_example; // The name that needs to be deleted
    +                              
    String *username = username_example; // The name that needs to be deleted
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -5417,15 +5137,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var username = username_example; // {String} The name that needs to be deleted
     
    @@ -5438,20 +5156,18 @@ var callback = function(error, data, response) {
       }
     };
     api.deleteUser(username, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -5474,17 +5190,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $username = username_example; // String | The name that needs to be deleted
     
     try {
    @@ -5492,8 +5205,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->deleteUser: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -5582,16 +5294,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/user/{username}"
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/user/{username}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -5610,14 +5319,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -5632,18 +5338,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -String *username = username_example; // The name that needs to be fetched. Use user1 for testing. 
    +                              
    String *username = username_example; // The name that needs to be fetched. Use user1 for testing. 
     
     UserApi *apiInstance = [[UserApi alloc] init];
     
    @@ -5657,15 +5359,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var username = username_example; // {String} The name that needs to be fetched. Use user1 for testing. 
     
    @@ -5678,20 +5378,18 @@ var callback = function(error, data, response) {
       }
     };
     api.getUserByName(username, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -5715,17 +5413,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $username = username_example; // String | The name that needs to be fetched. Use user1 for testing. 
     
     try {
    @@ -5734,8 +5429,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->getUserByName: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -5866,16 +5560,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/user/login?username=&password="
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -5895,14 +5586,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -5918,18 +5606,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -String *username = username_example; // The user name for login
    +                              
    String *username = username_example; // The user name for login
     String *password = password_example; // The password for login in clear text
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -5945,15 +5629,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var username = username_example; // {String} The user name for login
     
    @@ -5968,20 +5650,18 @@ var callback = function(error, data, response) {
       }
     };
     api.loginUser(username, password, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -6006,17 +5686,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $username = username_example; // String | The user name for login
     $password = password_example; // String | The password for login in clear text
     
    @@ -6026,8 +5703,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->loginUser: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -6201,16 +5877,13 @@ try {
    -
    
    -  curl -X get "http://petstore.swagger.io/v2/user/logout"
    -  
    +
    curl -X get "http://petstore.swagger.io/v2/user/logout"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -6227,14 +5900,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -6247,9 +5917,7 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    
    -  
    -
     UserApi *apiInstance = [[UserApi alloc] init];
     
     // Logs out current logged in user session
    @@ -6268,15 +5934,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var callback = function(error, data, response) {
       if (error) {
    @@ -6286,20 +5950,18 @@ var callback = function(error, data, response) {
       }
     };
     api.logoutUser(callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -6321,25 +5983,21 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     
     try {
         $api_instance->logoutUser();
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->logoutUser: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -6386,16 +6044,13 @@ try {
    -
    
    -  curl -X put "http://petstore.swagger.io/v2/user/{username}"
    -  
    +
    curl -X put "http://petstore.swagger.io/v2/user/{username}"
    -
    
    -  import io.swagger.client.*;
    +                            
    import io.swagger.client.*;
     import io.swagger.client.auth.*;
     import io.swagger.client.model.*;
    -import .UserApi;
    +import io.swagger.client.api.UserApi;
     
     import java.io.File;
     import java.util.*;
    @@ -6414,14 +6069,11 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  import .UserApi;
    +                            
    import io.swagger.client.api.UserApi;
     
     public class UserApiExample {
     
    @@ -6436,18 +6088,14 @@ public class UserApiExample {
                 e.printStackTrace();
             }
         }
    -}
    -
    -                            
    +}
    -
    
    -  
    -String *username = username_example; // name that need to be deleted
    +                              
    String *username = username_example; // name that need to be deleted
     User *body = ; // Updated user object
     
     UserApi *apiInstance = [[UserApi alloc] init];
    @@ -6460,15 +6108,13 @@ UserApi *apiInstance = [[UserApi alloc] init];
                                     NSLog(@"Error: %@", error);
                                 }
                             }];
    -
    -                              
    +
    -
    
    -  var  = require('');
    +                              
    var SwaggerPetstore = require('swagger_petstore');
     
    -var api = new .UserApi()
    +var api = new SwaggerPetstore.UserApi()
     
     var username = username_example; // {String} name that need to be deleted
     
    @@ -6483,20 +6129,18 @@ var callback = function(error, data, response) {
       }
     };
     api.updateUser(username, body, callback);
    -
    -                              
    +
    -
    
    -  using System;
    +                              
    using System;
     using System.Diagnostics;
    -using .Api;
    -using .Client;
    -using ;
    +using IO.Swagger.Api;
    +using IO.Swagger.Client;
    +using IO.Swagger.Model;
     
     namespace Example
     {
    @@ -6520,17 +6164,14 @@ namespace Example
                 }
             }
         }
    -}
    -
    -                              
    +}
    -
    
    -  <?php
     require_once(__DIR__ . '/vendor/autoload.php');
     
    -$api_instance = new io.swagger.client\Api\UserApi();
    +$api_instance = new Swagger\Client\Api\UserApi();
     $username = username_example; // String | name that need to be deleted
     $body = ; // User | Updated user object
     
    @@ -6539,8 +6180,7 @@ try {
     } catch (Exception $e) {
         echo 'Exception when calling UserApi->updateUser: ', $e->getMessage(), PHP_EOL;
     }
    -
    -                              
    +?>
    @@ -6663,7 +6303,7 @@ try {
    - Generated 2016-11-16T15:33:43.134-08:00 + Generated 2016-12-12T15:29:18.279-08:00
    From 2bf3d051a9ae1af89e3b83ba43aa66c5aa997ab7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 16 Dec 2016 18:14:55 +0800 Subject: [PATCH 182/269] update html2 sample --- samples/html2/index.html | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/html2/index.html b/samples/html2/index.html index 1cc445b3f32..26881d448da 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -3026,7 +3026,7 @@ public class PetApiExample { PetApi apiInstance = new PetApi(); Long petId = 789; // Long | ID of pet to update String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server - file file = /path/to/file.txt; // file | file to upload + File file = /path/to/file.txt; // File | file to upload try { ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); System.out.println(result); @@ -3047,7 +3047,7 @@ public class PetApiExample { PetApi apiInstance = new PetApi(); Long petId = 789; // Long | ID of pet to update String additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server - file file = /path/to/file.txt; // file | file to upload + File file = /path/to/file.txt; // File | file to upload try { ApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); System.out.println(result); @@ -3070,7 +3070,7 @@ public class PetApiExample { Long *petId = 789; // ID of pet to update String *additionalMetadata = additionalMetadata_example; // Additional data to pass to server (optional) -file *file = /path/to/file.txt; // file to upload (optional) +File *file = /path/to/file.txt; // file to upload (optional) PetApi *apiInstance = [[PetApi alloc] init]; @@ -3103,7 +3103,7 @@ var petId = 789; // {Long} ID of pet to update var opts = { 'additionalMetadata': additionalMetadata_example, // {String} Additional data to pass to server - 'file': /path/to/file.txt // {file} file to upload + 'file': /path/to/file.txt // {File} file to upload }; var callback = function(error, data, response) { @@ -3140,7 +3140,7 @@ namespace Example var apiInstance = new PetApi(); var petId = 789; // Long | ID of pet to update var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server (optional) - var file = new file(); // file | file to upload (optional) + var file = /path/to/file.txt; // File | file to upload (optional) try { @@ -3167,7 +3167,7 @@ Swagger\Client\Configuration::getDefaultConfiguration()->setAccessToken('YOUR_AC $api_instance = new Swagger\Client\Api\PetApi(); $petId = 789; // Long | ID of pet to update $additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server -$file = /path/to/file.txt; // file | file to upload +$file = /path/to/file.txt; // File | file to upload try { $result = $api_instance->uploadFile($petId, $additionalMetadata, $file); @@ -6303,7 +6303,7 @@ try {
    - Generated 2016-12-12T15:29:18.279-08:00 + Generated 2016-12-16T18:07:47.864+08:00
    From c6c8ffe4e0bf3ed7e1955167cf6e56465aa93480 Mon Sep 17 00:00:00 2001 From: Nicholas DiPiazza Date: Fri, 16 Dec 2016 05:04:13 -0600 Subject: [PATCH 183/269] Do not NPE when array properties items are not specified (#4063) --- .../io/swagger/codegen/languages/AbstractJavaCodegen.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index e33c596c06a..d20a36f7080 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -461,6 +461,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); + if (inner == null) { + return null; + } return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; @@ -480,6 +483,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } else { pattern = "new ArrayList<%s>()"; } + if (ap.getItems() == null) { + return null; + } return String.format(pattern, getTypeDeclaration(ap.getItems())); } else if (p instanceof MapProperty) { final MapProperty ap = (MapProperty) p; From 6af43dc720269c245c8342aa7a2d201c637f6bf9 Mon Sep 17 00:00:00 2001 From: Hamed Ramezanian Nik Date: Fri, 16 Dec 2016 11:07:00 +0000 Subject: [PATCH 184/269] [csharp] Escape special characters in the API doc (#4183) Special characters like <> should be HTML escaped. --- .../src/main/resources/csharp/api_doc.mustache | 2 +- .../petstore/csharp/SwaggerClient/IO.Swagger.sln | 10 +++++----- .../petstore/csharp/SwaggerClient/docs/FakeApi.md | 6 +++--- .../petstore/csharp/SwaggerClient/docs/PetApi.md | 4 ++-- .../petstore/csharp/SwaggerClient/docs/UserApi.md | 4 ++-- .../SwaggerClient/src/IO.Swagger/IO.Swagger.csproj | 2 +- 6 files changed, 14 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache index 8349db2e1c1..76ff45b2e61 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api_doc.mustache @@ -75,7 +75,7 @@ namespace Example {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isPrimitiveType}}**{{{dataType}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{{dataType}}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} {{/allParams}} ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index 0b538e4e73f..b7c1013e434 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{959A8039-E3B9-4660-A666-840955E4520C}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Debug|Any CPU.Build.0 = Debug|Any CPU -{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Release|Any CPU.ActiveCfg = Release|Any CPU -{108D4EC7-6EA0-4D25-A8EC-653076D76ADC}.Release|Any CPU.Build.0 = Release|Any CPU +{959A8039-E3B9-4660-A666-840955E4520C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{959A8039-E3B9-4660-A666-840955E4520C}.Debug|Any CPU.Build.0 = Debug|Any CPU +{959A8039-E3B9-4660-A666-840955E4520C}.Release|Any CPU.ActiveCfg = Release|Any CPU +{959A8039-E3B9-4660-A666-840955E4520C}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index 8dd5de759ee..de9d842ee06 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -209,11 +209,11 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enumFormStringArray** | [**List**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormStringArray** | [**List<string>**](string.md)| Form parameter enum test (string array) | [optional] **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] - **enumHeaderStringArray** | [**List**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderStringArray** | [**List<string>**](string.md)| Header parameter enum test (string array) | [optional] **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] - **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryStringArray** | [**List<string>**](string.md)| Query parameter enum test (string array) | [optional] **enumQueryString** | **string**| Query parameter enum test (string) | [optional] [default to -efg] **enumQueryInteger** | **int?**| Query parameter enum test (double) | [optional] **enumQueryDouble** | **double?**| Query parameter enum test (double) | [optional] diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md index de9223ef7a4..da77647d5d8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/PetApi.md @@ -192,7 +192,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List**](string.md)| Status values that need to be considered for filter | + **status** | [**List<string>**](string.md)| Status values that need to be considered for filter | ### Return type @@ -257,7 +257,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**List**](string.md)| Tags to filter by | + **tags** | [**List<string>**](string.md)| Tags to filter by | ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md index e016a7a5e30..b7fc0343d20 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/UserApi.md @@ -119,7 +119,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List**](User.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type @@ -180,7 +180,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List**](User.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 76d794700bf..43a0d972a0d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -11,7 +11,7 @@ Contact: apiteam@swagger.io Debug AnyCPU - {108D4EC7-6EA0-4D25-A8EC-653076D76ADC} + {959A8039-E3B9-4660-A666-840955E4520C} Library Properties IO.Swagger From 2172cfef84b5bcfd632ce013caea7a456fd11f8b Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 16 Dec 2016 19:41:54 +0800 Subject: [PATCH 185/269] add warning message for null inner type (map/array) (#4408) --- .../codegen/languages/AbstractJavaCodegen.java | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index d20a36f7080..2e6026bd014 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -462,12 +462,19 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); if (inner == null) { - return null; + LOGGER.warn(ap.getName() + "(array property) does not have a proper inner type defined"); + // TODO maybe better defaulting to StringProperty than returning null + return null; } return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); + if (inner == null) { + LOGGER.warn(mp.getName() + "(map property) does not have a proper inner type defined"); + // TODO maybe better defaulting to StringProperty than returning null + return null; + } return getSwaggerType(p) + ""; } return super.getTypeDeclaration(p); @@ -484,7 +491,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code pattern = "new ArrayList<%s>()"; } if (ap.getItems() == null) { - return null; + return null; } return String.format(pattern, getTypeDeclaration(ap.getItems())); } else if (p instanceof MapProperty) { @@ -495,6 +502,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } else { pattern = "new HashMap()"; } + if (ap.getAdditionalProperties() == null) { + return null; + } return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); } else if (p instanceof IntegerProperty) { IntegerProperty dp = (IntegerProperty) p; From 41c49341f2e66eff4ab1d82107ecefb096447433 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 16 Dec 2016 22:28:32 +0800 Subject: [PATCH 186/269] rename api documentation generator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1e7f4fd9d15..28bff841253 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ This is the swagger codegen project, which allows generation of API client libra - **API clients**: **ActionScript**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) - **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) -- **API documentations**: **HTML**, **Confluence Wiki** +- **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** Check out [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) for additional information about the OpenAPI project. From 6bf721f2e323684c41bbf6e82b031154810b381a Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 17 Dec 2016 00:29:06 +0800 Subject: [PATCH 187/269] add parameter as reserved keyword (#4410) --- .../io/swagger/codegen/languages/AbstractCSharpCodegen.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index da01ca6eae5..922e9213add 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -60,10 +60,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co setReservedWordsLowerCase( Arrays.asList( - // set client as a reserved word to avoid conflicts with IO.Swagger.Client + // set "client" as a reserved word to avoid conflicts with IO.Swagger.Client // this is a workaround and can be removed if c# api client is updated to use // fully qualified name - "client", + "client", "parameter", // local variable names in API methods (endpoints) "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", From 537dcbe03612e0eac3e1d8f8e285ed5bc8cf7871 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 17 Dec 2016 00:40:56 +0800 Subject: [PATCH 188/269] fix https://github.com/airbnb/javascript/ --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 67d2b7f0ffb..b187c39192c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,7 +35,7 @@ Code change should conform to the programming style guide of the respective lang - Clojure: https://github.com/bbatsov/clojure-style-guide - Haskell: https://github.com/tibbe/haskell-style-guide/blob/master/haskell-style.md - Java: https://google.github.io/styleguide/javaguide.html -- JavaScript: https://github.com/airbnb/javascript/tree/master/es5 +- JavaScript: https://github.com/airbnb/javascript/ - Groovy: http://groovy-lang.org/style-guide.html - Go: https://github.com/golang/go/wiki/CodeReviewComments - ObjC: https://github.com/NYTimes/objective-c-style-guide From 7e67307bb4f14dac224a0159a7b54443f5957133 Mon Sep 17 00:00:00 2001 From: Hamed Ramezanian Nik Date: Sat, 17 Dec 2016 02:58:08 +0000 Subject: [PATCH 189/269] Add AYLIEN company to the list (#4412) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 28bff841253..25d006bc879 100644 --- a/README.md +++ b/README.md @@ -755,6 +755,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) - [Avenida Compras S.A.](https://www.avenida.com.ar) +- [AYLIEN](http://aylien.com/) - [Balance Internet](https://www.balanceinternet.com.au/) - [beemo](http://www.beemo.eu) - [bitly](https://bitly.com) From 8ccf9828e425da79b90b3a985fc37bc672050be4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 18 Dec 2016 17:20:10 +0800 Subject: [PATCH 190/269] [Python] add hasConsumes/hasProduces to Python API template (#4419) * add hasConsumes/hasProduces to python api template * remove unused code in python * fix isFile in the api doc (python) --- .../src/main/resources/python/api.mustache | 7 ++- .../main/resources/python/api_doc.mustache | 2 +- samples/client/petstore/python/README.md | 2 +- .../client/petstore/python/docs/FakeApi.md | 4 ++ .../python/petstore_api/apis/fake_api.py | 13 ++--- .../python/petstore_api/apis/pet_api.py | 40 ------------- .../python/petstore_api/apis/store_api.py | 28 ---------- .../python/petstore_api/apis/user_api.py | 56 ------------------- 8 files changed, 14 insertions(+), 138 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index f8b5d564ab6..0088f2bcec7 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -196,17 +196,18 @@ class {{classname}}(object): if '{{paramName}}' in params: body_params = params['{{paramName}}'] {{/bodyParam}} - + {{#hasProduces}} # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept([{{#produces}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) - if not header_params['Accept']: - del header_params['Accept'] + {{/hasProduces}} + {{#hasConsumes}} # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type([{{#consumes}}'{{{mediaType}}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + {{/hasConsumes}} # Authentication setting auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] diff --git a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache index f9a212c19e1..689e9ff2bb7 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_doc.mustache @@ -53,7 +53,7 @@ except ApiException as e: {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} -{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{baseType}}.md){{/isPrimitiveType}}{{/isFile}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} {{/allParams}} ### Return type diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index fd16a182ca2..a131676c829 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build package: class io.swagger.codegen.languages.PythonClientCodegen +- Build package: io.swagger.codegen.languages.PythonClientCodegen ## Requirements. diff --git a/samples/client/petstore/python/docs/FakeApi.md b/samples/client/petstore/python/docs/FakeApi.md index cad45b8f219..0a6770ff67d 100644 --- a/samples/client/petstore/python/docs/FakeApi.md +++ b/samples/client/petstore/python/docs/FakeApi.md @@ -14,6 +14,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```python from __future__ import print_statement @@ -137,6 +139,8 @@ void (empty response body) To test enum parameters +To test enum parameters + ### Example ```python from __future__ import print_statement diff --git a/samples/client/petstore/python/petstore_api/apis/fake_api.py b/samples/client/petstore/python/petstore_api/apis/fake_api.py index 31857574da7..95fc5c69362 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_api.py @@ -43,6 +43,7 @@ class FakeApi(object): def test_client_model(self, body, **kwargs): """ To test \"client\" model + To test \"client\" model This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -68,6 +69,7 @@ class FakeApi(object): def test_client_model_with_http_info(self, body, **kwargs): """ To test \"client\" model + To test \"client\" model This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -119,12 +121,9 @@ class FakeApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -316,12 +315,9 @@ class FakeApi(object): form_params.append(('callback', params['param_callback'])) body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml; charset=utf-8', 'application/json; charset=utf-8']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -348,6 +344,7 @@ class FakeApi(object): def test_enum_parameters(self, **kwargs): """ To test enum parameters + To test enum parameters This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -380,6 +377,7 @@ class FakeApi(object): def test_enum_parameters_with_http_info(self, **kwargs): """ To test enum parameters + To test enum parameters This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -452,12 +450,9 @@ class FakeApi(object): form_params.append(('enum_query_double', params['enum_query_double'])) body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['*/*']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ diff --git a/samples/client/petstore/python/petstore_api/apis/pet_api.py b/samples/client/petstore/python/petstore_api/apis/pet_api.py index d1e45a33def..d3d5e96025a 100644 --- a/samples/client/petstore/python/petstore_api/apis/pet_api.py +++ b/samples/client/petstore/python/petstore_api/apis/pet_api.py @@ -121,12 +121,9 @@ class PetApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -235,16 +232,9 @@ class PetApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] @@ -346,16 +336,9 @@ class PetApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] @@ -457,16 +440,9 @@ class PetApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = ['petstore_auth'] @@ -567,16 +543,9 @@ class PetApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = ['api_key'] @@ -677,12 +646,9 @@ class PetApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -795,12 +761,9 @@ class PetApi(object): form_params.append(('status', params['status'])) body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -913,12 +876,9 @@ class PetApi(object): local_var_files['file'] = params['file'] body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ diff --git a/samples/client/petstore/python/petstore_api/apis/store_api.py b/samples/client/petstore/python/petstore_api/apis/store_api.py index 1764a9172b0..089342ed275 100644 --- a/samples/client/petstore/python/petstore_api/apis/store_api.py +++ b/samples/client/petstore/python/petstore_api/apis/store_api.py @@ -123,16 +123,9 @@ class StoreApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -225,16 +218,9 @@ class StoreApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = ['api_key'] @@ -339,16 +325,9 @@ class StoreApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -449,16 +428,9 @@ class StoreApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] diff --git a/samples/client/petstore/python/petstore_api/apis/user_api.py b/samples/client/petstore/python/petstore_api/apis/user_api.py index 0ad16268c34..6b620aa63af 100644 --- a/samples/client/petstore/python/petstore_api/apis/user_api.py +++ b/samples/client/petstore/python/petstore_api/apis/user_api.py @@ -121,16 +121,9 @@ class UserApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -231,16 +224,9 @@ class UserApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -341,16 +327,9 @@ class UserApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -451,16 +430,9 @@ class UserApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -561,16 +533,9 @@ class UserApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -678,16 +643,9 @@ class UserApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -780,16 +738,9 @@ class UserApi(object): local_var_files = {} body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] @@ -897,16 +848,9 @@ class UserApi(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/xml', 'application/json']) - if not header_params['Accept']: - del header_params['Accept'] - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.\ - select_header_content_type([]) # Authentication setting auth_settings = [] From 7fd895b37d997466956cd95acb551b038fed7c83 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 18 Dec 2016 19:02:26 +0800 Subject: [PATCH 191/269] fix isPrimitiveType for file --- .../io/swagger/codegen/DefaultCodegen.java | 3 +- .../petstore/php/SwaggerClient-php/README.md | 2 +- .../php/SwaggerClient-php/docs/Api/FakeApi.md | 8 +++- .../php/SwaggerClient-php/lib/Api/FakeApi.php | 20 +++++----- .../SwaggerClient-php/lib/Api/StoreApi.php | 8 ++-- .../lib/Model/FormatTest.php | 40 +++++++++---------- 6 files changed, 43 insertions(+), 38 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 1e3cc438126..61a88955700 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -3309,7 +3309,8 @@ public class DefaultCodegen { parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isFile)) { parameter.isFile = true; - parameter.isPrimitiveType = true; + // file is *not* a primitive type + //parameter.isPrimitiveType = true; } else if (Boolean.TRUE.equals(property.isDate)) { parameter.isDate = true; parameter.isPrimitiveType = true; diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index 068d01c9b10..a8d469f5c02 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 -- Build package: class io.swagger.codegen.languages.PhpClientCodegen +- Build package: io.swagger.codegen.languages.PhpClientCodegen ## Requirements diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md index 2ab4c088caa..714b23996e6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/FakeApi.md @@ -14,6 +14,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```php 100.0)) { - throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.0.'); + if (!is_null($integer) && ($integer > 100)) { + throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 100.'); } - if (!is_null($integer) && ($integer < 10.0)) { - throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.0.'); + if (!is_null($integer) && ($integer < 10)) { + throw new \InvalidArgumentException('invalid value for "$integer" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 10.'); } - if (!is_null($int32) && ($int32 > 200.0)) { - throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.0.'); + if (!is_null($int32) && ($int32 > 200)) { + throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be smaller than or equal to 200.'); } - if (!is_null($int32) && ($int32 < 20.0)) { - throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.0.'); + if (!is_null($int32) && ($int32 < 20)) { + throw new \InvalidArgumentException('invalid value for "$int32" when calling FakeApi.testEndpointParameters, must be bigger than or equal to 20.'); } if (!is_null($float) && ($float > 987.6)) { @@ -399,7 +399,7 @@ class FakeApi * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) - * @param float $enum_query_integer Query parameter enum test (double) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @throws \Swagger\Client\ApiException on non-2xx response * @return void @@ -421,7 +421,7 @@ class FakeApi * @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) * @param string[] $enum_query_string_array Query parameter enum test (string array) (optional) * @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) - * @param float $enum_query_integer Query parameter enum test (double) (optional) + * @param int $enum_query_integer Query parameter enum test (double) (optional) * @param double $enum_query_double Query parameter enum test (double) (optional) * @throws \Swagger\Client\ApiException on non-2xx response * @return array of null, HTTP status code, HTTP response headers (array of strings) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 945b9b3fb1f..7070313661d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -279,11 +279,11 @@ class StoreApi if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } - if (($order_id > 5.0)) { - throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.0.'); + if (($order_id > 5)) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be smaller than or equal to 5.'); } - if (($order_id < 1.0)) { - throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.0.'); + if (($order_id < 1)) { + throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.getOrderById, must be bigger than or equal to 1.'); } // parse inputs diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 524904f2af7..29fc74a86eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -191,20 +191,20 @@ class FormatTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; - if (!is_null($this->container['integer']) && ($this->container['integer'] > 100.0)) { - $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100.0."; + if (!is_null($this->container['integer']) && ($this->container['integer'] > 100)) { + $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100."; } - if (!is_null($this->container['integer']) && ($this->container['integer'] < 10.0)) { - $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10.0."; + if (!is_null($this->container['integer']) && ($this->container['integer'] < 10)) { + $invalid_properties[] = "invalid value for 'integer', must be bigger than or equal to 10."; } - if (!is_null($this->container['int32']) && ($this->container['int32'] > 200.0)) { - $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200.0."; + if (!is_null($this->container['int32']) && ($this->container['int32'] > 200)) { + $invalid_properties[] = "invalid value for 'int32', must be smaller than or equal to 200."; } - if (!is_null($this->container['int32']) && ($this->container['int32'] < 20.0)) { - $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20.0."; + if (!is_null($this->container['int32']) && ($this->container['int32'] < 20)) { + $invalid_properties[] = "invalid value for 'int32', must be bigger than or equal to 20."; } if ($this->container['number'] === null) { @@ -266,16 +266,16 @@ class FormatTest implements ArrayAccess */ public function valid() { - if ($this->container['integer'] > 100.0) { + if ($this->container['integer'] > 100) { return false; } - if ($this->container['integer'] < 10.0) { + if ($this->container['integer'] < 10) { return false; } - if ($this->container['int32'] > 200.0) { + if ($this->container['int32'] > 200) { return false; } - if ($this->container['int32'] < 20.0) { + if ($this->container['int32'] < 20) { return false; } if ($this->container['number'] === null) { @@ -338,11 +338,11 @@ class FormatTest implements ArrayAccess public function setInteger($integer) { - if (!is_null($integer) && ($integer > 100.0)) { - throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.0.'); + if (!is_null($integer) && ($integer > 100)) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be smaller than or equal to 100.'); } - if (!is_null($integer) && ($integer < 10.0)) { - throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.0.'); + if (!is_null($integer) && ($integer < 10)) { + throw new \InvalidArgumentException('invalid value for $integer when calling FormatTest., must be bigger than or equal to 10.'); } $this->container['integer'] = $integer; @@ -367,11 +367,11 @@ class FormatTest implements ArrayAccess public function setInt32($int32) { - if (!is_null($int32) && ($int32 > 200.0)) { - throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.0.'); + if (!is_null($int32) && ($int32 > 200)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be smaller than or equal to 200.'); } - if (!is_null($int32) && ($int32 < 20.0)) { - throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.0.'); + if (!is_null($int32) && ($int32 < 20)) { + throw new \InvalidArgumentException('invalid value for $int32 when calling FormatTest., must be bigger than or equal to 20.'); } $this->container['int32'] = $int32; From da1e07af21a1e819fade3037c2e879edef41f943 Mon Sep 17 00:00:00 2001 From: Matthieu Chase Heimer Date: Mon, 19 Dec 2016 13:25:10 -0600 Subject: [PATCH 192/269] Update DefaultGenerator.java to call close() Need to call out.close() after IOUtils.copy(in, out); when writing supporting files. --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 5f11f99d99c..228be1a3ef5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -526,6 +526,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (in != null) { LOGGER.info("writing file " + outputFile); IOUtils.copy(in, out); + out.close(); } else { LOGGER.error("can't open " + templateFile + " for input"); } From ff70105484c8ebefd3aa1cbdc1a62c7ae598d91e Mon Sep 17 00:00:00 2001 From: Johan Nystrom Date: Tue, 20 Dec 2016 17:02:45 +0900 Subject: [PATCH 193/269] Fix CSV collection parameter issues for scalatra server (#4426) * Fix scalatra handling of CSV query parameters * Ran petstore for scalatra server --- .../scalatra/queryParamOperation.mustache | 10 +- .../petstore-security-test/scala/gradlew.bat | 180 +++++++++--------- .../petstore-security-test/scala/pom.xml | 2 +- .../scala/io/swagger/client/ApiInvoker.scala | 20 +- .../scala/io/swagger/client/api/FakeApi.scala | 51 ++--- .../io/swagger/client/model/ModelReturn.scala | 27 +-- .../scala/com/wordnik/client/api/PetApi.scala | 16 +- 7 files changed, 132 insertions(+), 174 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache b/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache index 832bbed2030..2e7152f53bb 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/queryParamOperation.mustache @@ -1,13 +1,13 @@ {{#isQueryParam}} {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") - val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + val {{paramName}} = if("{{collectionFormat}}" == "default" || "{{collectionFormat}}" == "csv") { {{paramName}}String match { - case Some(str) => str.split(",") - case None => List() + case Some(str) => str.split(",").toSeq + case None => Seq() } } else - List() + Seq() {{/collectionFormat}} {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} - {{/isQueryParam}} \ No newline at end of file + {{/isQueryParam}} diff --git a/samples/client/petstore-security-test/scala/gradlew.bat b/samples/client/petstore-security-test/scala/gradlew.bat index 72d362dafd8..5f192121eb4 100644 --- a/samples/client/petstore-security-test/scala/gradlew.bat +++ b/samples/client/petstore-security-test/scala/gradlew.bat @@ -1,90 +1,90 @@ -@if "%DEBUG%" == "" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= - -set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto init - -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto init - -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. - -goto fail - -:init -@rem Get command-line arguments, handling Windows variants - -if not "%OS%" == "Windows_NT" goto win9xME_args -if "%@eval[2+2]" == "4" goto 4NT_args - -:win9xME_args -@rem Slurp the command line arguments. -set CMD_LINE_ARGS= -set _SKIP=2 - -:win9xME_args_slurp -if "x%~1" == "x" goto execute - -set CMD_LINE_ARGS=%* -goto execute - -:4NT_args -@rem Get arguments from the 4NT Shell from JP Software -set CMD_LINE_ARGS=%$ - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore-security-test/scala/pom.xml b/samples/client/petstore-security-test/scala/pom.xml index 5b036cd8fc1..27055cbbdc6 100644 --- a/samples/client/petstore-security-test/scala/pom.xml +++ b/samples/client/petstore-security-test/scala/pom.xml @@ -210,7 +210,7 @@ 1.2 2.2 1.19 - 1.5.8 + 1.5.9 1.0.5 1.0.0 2.4.2 diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala index 22f3dac7cf8..c9577f39ef3 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -1,25 +1,13 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package io.swagger.client diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala index ce6f4eee77f..c5ee2da0a29 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -1,25 +1,13 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package io.swagger.client.api @@ -37,7 +25,7 @@ import java.util.Date import scala.collection.mutable.HashMap -class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r", +class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r", defApiInvoker: ApiInvoker = ApiInvoker) { var basePath = defBasePath var apiInvoker = defApiInvoker @@ -45,37 +33,32 @@ class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \ def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value /** - * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) * @return void */ - def testCodeInject * ' " =end rn n r (testCodeInjectEndRnNR: String) = { + def testCodeInject * ' " =end rn n r(testCodeInjectEndRnNR: Option[String] = None) = { // create path and map variables - val path = "/fake".replaceAll("\\{format\\}","json") - val contentTypes = List("application/json", "*/ ' =end - - ", "application/json") + val path = "/fake".replaceAll("\\{format\\}", "json") + + val contentTypes = List("application/json", "*_/ ' =end -- ") val contentType = contentTypes(0) - // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] val formParams = new HashMap[String, String] - + var postBody: AnyRef = null - if(contentType.startsWith("multipart/form-data")) { - val mp = new FormDataMultiPart() - - mp.field("test code inject */ ' " =end \r\n \n \r", testCodeInjectEndRnNR.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) - + if (contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart + testCodeInjectEndRnNR.map(paramVal => mp.field("test code inject */ ' " =end -- \r\n \n \r", paramVal.toString, MediaType.MULTIPART_FORM_DATA_TYPE)) postBody = mp - } - else { - formParams += "test code inject */ ' " =end \r\n \n \r" -> testCodeInjectEndRnNR.toString() + } else { + testCodeInjectEndRnNR.map(paramVal => formParams += "test code inject */ ' " =end -- \r\n \n \r" -> paramVal.toString) } try { diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala index 08aaff0573a..16ddb5e6062 100644 --- a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -1,32 +1,19 @@ /** - * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * Swagger Petstore *_/ ' \" =end -- \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end -- * - * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r - * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * OpenAPI spec version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. */ package io.swagger.client.model - - case class ModelReturn ( - /* property description *_/ ' \" =end \\r\\n \\n \\r */ - _return: Integer) + /* property description *_/ ' \" =end -- \\r\\n \\n \\r */ + _return: Integer +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 62f1dbcefd3..7c6d352ae5d 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -87,14 +87,14 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet val statusString = params.getAs[String]("status") - val status = if("csv".equals("default")) { + val status = if("csv" == "default" || "csv" == "csv") { statusString match { - case Some(str) => str.split(",") - case None => List() + case Some(str) => str.split(",").toSeq + case None => Seq() } } else - List() + Seq() println("status: " + status) @@ -111,14 +111,14 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet val tagsString = params.getAs[String]("tags") - val tags = if("csv".equals("default")) { + val tags = if("csv" == "default" || "csv" == "csv") { tagsString match { - case Some(str) => str.split(",") - case None => List() + case Some(str) => str.split(",").toSeq + case None => Seq() } } else - List() + Seq() println("tags: " + tags) From 36b97c22afd318130da9d8f467d76877ff448478 Mon Sep 17 00:00:00 2001 From: Greg Rashkevitch Date: Tue, 20 Dec 2016 10:10:47 +0200 Subject: [PATCH 194/269] Fix warning docs return type (#4429) * Objective C: Fix compilation warnings If returnType is not provided, set the @return as void * Run the `./bin/objc-petstore.sh` * OBJECTIVE C SDK: Remove the return line for methods that return nothing all together * obj-c sdk: Updated petstore sample --- .../src/main/resources/objc/api-header.mustache | 4 ++-- samples/client/petstore/objc/default/README.md | 2 +- .../objc/default/SwaggerClient/Api/SWGPetApi.h | 5 ----- .../objc/default/SwaggerClient/Api/SWGPetApi.m | 2 +- .../objc/default/SwaggerClient/Api/SWGStoreApi.h | 1 - .../objc/default/SwaggerClient/Api/SWGUserApi.h | 6 ------ samples/client/petstore/objc/default/docs/SWGPetApi.md | 10 +++++----- 7 files changed, 9 insertions(+), 21 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index abe4cf64eb0..2bd3cd2f490 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -21,8 +21,8 @@ extern NSInteger k{{classname}}MissingParamErrorCode; /// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} /// {{/allParams}}{{#responses}} /// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} -/// -/// @return {{{returnType}}} +///{{#returnType}} +/// @return {{{returnType}}}{{/returnType}} -(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index 20e27d6fa0a..c59d5182287 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build package: class io.swagger.codegen.languages.ObjcClientCodegen +- Build package: io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index e20ae3f380e..b5500c2377b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -30,7 +30,6 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// code:405 message:"Invalid input" /// -/// @return -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; @@ -43,7 +42,6 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// code:400 message:"Invalid pet value" /// -/// @return -(NSNumber*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; @@ -98,7 +96,6 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" /// -/// @return -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; @@ -112,7 +109,6 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// code:405 message:"Invalid input" /// -/// @return -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status @@ -128,7 +124,6 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// code:0 message:"successful operation" /// -/// @return -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 76d707cdb42..16d1541471b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -376,7 +376,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h index 4ee54d53306..822701c3c41 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h @@ -31,7 +31,6 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode; /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" /// -/// @return -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h index d3965216137..630f6679a81 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h @@ -30,7 +30,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// /// code:0 message:"successful operation" /// -/// @return -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; @@ -42,7 +41,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// /// code:0 message:"successful operation" /// -/// @return -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; @@ -54,7 +52,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// /// code:0 message:"successful operation" /// -/// @return -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; @@ -67,7 +64,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" /// -/// @return -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; @@ -107,7 +103,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// /// code:0 message:"successful operation" /// -/// @return -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; @@ -121,7 +116,6 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" /// -/// @return -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index 9971ffff450..c4275413c62 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -246,14 +246,14 @@ Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error cond ```objc SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; + // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; -// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; - NSNumber* petId = @789; // ID of pet that needs to be fetched @@ -283,7 +283,7 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) ### HTTP request headers @@ -447,7 +447,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **NSNumber***| ID of pet to update | **additionalMetadata** | **NSString***| Additional data to pass to server | [optional] - **file** | **NSURL***| file to upload | [optional] + **file** | **NSURL*****NSURL***| file to upload | [optional] ### Return type From 7f980cd9dd4d3ba5101a4ac00cc798cd078e6017 Mon Sep 17 00:00:00 2001 From: Vincent Giersch Date: Tue, 20 Dec 2016 02:35:03 -0600 Subject: [PATCH 195/269] fix(swift3): lowercase enum value before checking reserved words (#4357) Signed-off-by: Vincent Giersch --- .../codegen/languages/Swift3Codegen.java | 33 ++++++++++--------- .../codegen/swift3/Swift3CodegenTest.java | 9 +++-- .../Classes/Swaggers/APIs/FakeAPI.swift | 6 ++-- .../Classes/Swaggers/Models/ClassModel.swift | 24 ++++++++++++++ .../Classes/Swaggers/Models/OuterEnum.swift | 17 ++++++++++ 5 files changed, 68 insertions(+), 21 deletions(-) create mode 100644 samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift create mode 100644 samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 8810b2790c6..03327dc9cd7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -518,19 +518,20 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); } - // Camelize only when we have a structure defined below - Boolean camelized = false; - if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { - name = camelize(name, true); - camelized = true; - } - - // Reserved Name - if (isReservedWord(name)) { - return escapeReservedWord(name); + // Camelize only when we have a structure defined below + Boolean camelized = false; + if (name.matches("[A-Z][a-z0-9]+[a-zA-Z0-9]*")) { + name = camelize(name, true); + camelized = true; } - // Check for numerical conversions + // Reserved Name + String nameLowercase = StringUtils.lowerCase(name); + if (isReservedWord(nameLowercase)) { + return escapeReservedWord(nameLowercase); + } + + // Check for numerical conversions if ("Int".equals(datatype) || "Int32".equals(datatype) || "Int64".equals(datatype) || "Float".equals(datatype) || "Double".equals(datatype)) { String varName = "number" + camelize(name); @@ -540,11 +541,11 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { return varName; } - // If we have already camelized the word, don't progress - // any further - if (camelized) { - return name; - } + // If we have already camelized the word, don't progress + // any further + if (camelized) { + return name; + } char[] separators = {'-', '_', ' ', ':', '(', ')'}; return camelize(WordUtils.capitalizeFully(StringUtils.lowerCase(name), separators).replaceAll("[-_ :\\(\\)]", ""), true); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java index b933b064bb5..6fd6afa66f2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/swift3/Swift3CodegenTest.java @@ -13,14 +13,19 @@ public class Swift3CodegenTest { Swift3Codegen swiftCodegen = new Swift3Codegen(); + @Test + public void testCapitalizedReservedWord() throws Exception { + Assert.assertEquals(swiftCodegen.toEnumVarName("AS", null), "_as"); + } + @Test public void testReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public"); + Assert.assertEquals(swiftCodegen.toEnumVarName("Public", null), "_public"); } @Test public void shouldNotBreakNonReservedWord() throws Exception { - Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error"); + Assert.assertEquals(swiftCodegen.toEnumVarName("Error", null), "error"); } @Test diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 7ff3c6e4202..f81a52cb9b8 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -172,7 +172,7 @@ open class FakeAPI: APIBase { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } @@ -192,14 +192,14 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:Any?] = [ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger + "enum_query_integer": enumQueryInteger?.encodeToJSON() ] let parameters = APIHelper.rejectNil(nillableParameters) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift new file mode 100644 index 00000000000..a34c950a19e --- /dev/null +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/ClassModel.swift @@ -0,0 +1,24 @@ +// +// ClassModel.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing model with \"_class\" property */ +open class ClassModel: JSONEncodable { + public var _class: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["_class"] = self._class + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift new file mode 100644 index 00000000000..3f6e50251e6 --- /dev/null +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/OuterEnum.swift @@ -0,0 +1,17 @@ +// +// OuterEnum.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +public enum OuterEnum: String { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + + func encodeToJSON() -> Any { return self.rawValue } +} From 204c05442dd0dd5d16f32805e67b9fb0b1c94e1d Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 20 Dec 2016 19:13:03 +0800 Subject: [PATCH 196/269] [ObjC] minor code style enhancement to ObjC API client (#4437) * minor code style enhancement to objc api client * update petstore sample * remove datatype from docstring (objc) --- .../src/main/resources/objc/api-body.mustache | 15 +++-- .../main/resources/objc/api-header.mustache | 21 ++++--- .../client/petstore/objc/core-data/README.md | 2 +- .../core-data/SwaggerClient/Api/SWGPetApi.h | 29 --------- .../core-data/SwaggerClient/Api/SWGPetApi.m | 60 +++++++++--------- .../core-data/SwaggerClient/Api/SWGStoreApi.h | 13 ---- .../core-data/SwaggerClient/Api/SWGStoreApi.m | 26 ++++---- .../core-data/SwaggerClient/Api/SWGUserApi.h | 30 --------- .../core-data/SwaggerClient/Api/SWGUserApi.m | 50 +++++++-------- .../default/SwaggerClient/Api/SWGPetApi.h | 24 ------- .../default/SwaggerClient/Api/SWGPetApi.m | 62 +++++++++---------- .../default/SwaggerClient/Api/SWGStoreApi.h | 12 ---- .../default/SwaggerClient/Api/SWGStoreApi.m | 26 ++++---- .../default/SwaggerClient/Api/SWGUserApi.h | 24 ------- .../default/SwaggerClient/Api/SWGUserApi.m | 50 +++++++-------- .../petstore/objc/default/docs/SWGPetApi.md | 10 +-- 16 files changed, 166 insertions(+), 288 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 57fdc4ae6a7..4d3148bdbb6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -75,11 +75,17 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{{summary}}} /// {{{notes}}} -/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{#allParams}} +/// @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} /// -/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} -/// --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +{{/allParams}} +{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} +{{/responses}} +{{#returnType}} +/// @return {{{returnType}}} +{{/returnType}} +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -181,6 +187,5 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/operation}} -{{newline}} {{/operations}} @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 2bd3cd2f490..68c987633f4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -16,18 +16,23 @@ extern NSInteger k{{classname}}MissingParamErrorCode; {{#operations}} {{#operation}} /// {{{summary}}} -/// {{#notes}}{{{notes}}}{{/notes}} +{{#notes}} +/// {{{notes}}} +{{/notes}} /// -/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -/// {{/allParams}}{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} -///{{#returnType}} -/// @return {{{returnType}}}{{/returnType}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +{{#allParams}} +/// @param {{paramName}} {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} +{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} +{{/responses}} +{{#returnType}} +/// @return {{{returnType}}} +{{/returnType}} +-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; -{{newline}} {{/operation}} {{/operations}} diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index 20e27d6fa0a..c59d5182287 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build package: class io.swagger.codegen.languages.ObjcClientCodegen +- Build package: io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h index e20ae3f380e..719d193130b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h @@ -27,113 +27,84 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// /// @param body Pet object that needs to be added to the store (optional) -/// /// code:405 message:"Invalid input" -/// -/// @return -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; - /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) -/// /// code:400 message:"Invalid pet value" -/// -/// @return -(NSNumber*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; - /// Finds Pets by status /// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" -/// /// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; - /// Finds Pets by tags /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" -/// /// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; - /// 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 -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" -/// /// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; - /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) -/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" -/// -/// @return -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; - /// 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 (optional) /// @param status Updated status of the pet (optional) -/// /// code:405 message:"Invalid input" -/// -/// @return -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; - /// uploads an image /// /// /// @param petId ID of pet to update /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) -/// /// code:0 message:"successful operation" -/// -/// @return -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index 76d707cdb42..fb0421c81fd 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -72,10 +72,9 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) -/// -/// @returns void +/// @param body Pet object that needs to be added to the store (optional) /// +/// code:405 message:"Invalid input" -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -131,12 +130,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) -/// -/// @returns void +/// @param apiKey (optional) /// +/// code:400 message:"Invalid pet value" -(NSNumber*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { @@ -209,10 +207,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Finds Pets by status /// Multiple status values can be provided with comma separated strings -/// @param status Status values that need to be considered for filter (optional, default to available) -/// -/// @returns NSArray* +/// @param status Status values that need to be considered for filter (optional, default to available) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid status value" +/// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -271,10 +270,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Finds Pets by tags /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -/// @param tags Tags to filter by (optional) -/// -/// @returns NSArray* +/// @param tags Tags to filter by (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid tag value" +/// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -333,10 +333,12 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns SWGPet* +/// @param petId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found" +/// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set @@ -405,10 +407,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) -/// -/// @returns void +/// @param body Pet object that needs to be added to the store (optional) /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found", +/// code:405 message:"Validation exception" -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -464,14 +467,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) -/// -/// @returns void +/// @param status Updated status of the pet (optional) /// +/// code:405 message:"Invalid input" -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status @@ -548,14 +550,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) -/// -/// @returns void +/// @param file file to upload (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file @@ -628,5 +629,4 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h index 4ee54d53306..3e101bed9a7 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h @@ -27,52 +27,39 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode; /// 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 -/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" -/// -/// @return -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; - /// Returns pet inventories by status /// Returns a map of status codes to quantities /// -/// /// code:200 message:"successful operation" -/// /// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; - /// 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 -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" -/// /// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" -/// /// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m index e5964200f20..b86920b29e2 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m @@ -72,10 +72,10 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns void +/// @param orderId ID of the order that needs to be deleted /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set @@ -144,8 +144,8 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// @returns NSDictionary* -/// +/// code:200 message:"successful operation" +/// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -200,10 +200,12 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns SWGOrder* +/// @param orderId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" +/// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set @@ -272,10 +274,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) -/// -/// @returns SWGOrder* +/// @param body order placed for purchasing the pet (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid Order" +/// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -329,5 +332,4 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h index d3965216137..f0b5e37550b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h @@ -27,105 +27,75 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// This can only be done by the logged in user. /// /// @param body Created user object (optional) -/// /// code:0 message:"successful operation" -/// -/// @return -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; - /// Creates list of users with given input array /// /// /// @param body List of user object (optional) -/// /// code:0 message:"successful operation" -/// -/// @return -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; - /// Creates list of users with given input array /// /// /// @param body List of user object (optional) -/// /// code:0 message:"successful operation" -/// -/// @return -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; - /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted -/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" -/// -/// @return -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; - /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" -/// /// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; - /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" -/// /// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; - /// Logs out current logged in user session /// /// -/// /// code:0 message:"successful operation" -/// -/// @return -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; - /// 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 (optional) -/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" -/// -/// @return -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m index 6ffb578ed76..df056030b75 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m @@ -72,10 +72,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) -/// -/// @returns void +/// @param body Created user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -131,10 +130,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) -/// -/// @returns void +/// @param body List of user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -190,10 +188,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) -/// -/// @returns void +/// @param body List of user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -249,10 +246,10 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted -/// -/// @returns void +/// @param username The name that needs to be deleted /// +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -321,10 +318,12 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. -/// -/// @returns SWGUser* +/// @param username The name that needs to be fetched. Use user1 for testing. /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" +/// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set @@ -393,12 +392,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) -/// -/// @returns NSString* +/// @param password The password for login in clear text (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username/password supplied" +/// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { @@ -460,8 +460,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs out current logged in user session /// -/// @returns void -/// +/// code:0 message:"successful operation" -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -516,12 +515,12 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) -/// -/// @returns void +/// @param body Updated user object (optional) /// +/// code:400 message:"Invalid user supplied", +/// code:404 message:"User not found" -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { @@ -590,5 +589,4 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index b5500c2377b..719d193130b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -27,108 +27,84 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// /// @param body Pet object that needs to be added to the store (optional) -/// /// code:405 message:"Invalid input" -/// -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; - /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) -/// /// code:400 message:"Invalid pet value" -/// -(NSNumber*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; - /// Finds Pets by status /// Multiple status values can be provided with comma separated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" -/// /// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; - /// Finds Pets by tags /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" -/// /// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; - /// 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 -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" -/// /// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; - /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) -/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" -/// -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; - /// 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 (optional) /// @param status Updated status of the pet (optional) -/// /// code:405 message:"Invalid input" -/// -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; - /// uploads an image /// /// /// @param petId ID of pet to update /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) -/// /// code:0 message:"successful operation" -/// -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 16d1541471b..fb0421c81fd 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -72,10 +72,9 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) -/// -/// @returns void +/// @param body Pet object that needs to be added to the store (optional) /// +/// code:405 message:"Invalid input" -(NSNumber*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -131,12 +130,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) -/// -/// @returns void +/// @param apiKey (optional) /// +/// code:400 message:"Invalid pet value" -(NSNumber*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { @@ -209,10 +207,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Finds Pets by status /// Multiple status values can be provided with comma separated strings -/// @param status Status values that need to be considered for filter (optional, default to available) -/// -/// @returns NSArray* +/// @param status Status values that need to be considered for filter (optional, default to available) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid status value" +/// @return NSArray* -(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -271,10 +270,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Finds Pets by tags /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -/// @param tags Tags to filter by (optional) -/// -/// @returns NSArray* +/// @param tags Tags to filter by (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid tag value" +/// @return NSArray* -(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -333,10 +333,12 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns SWGPet* +/// @param petId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found" +/// @return SWGPet* -(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set @@ -376,7 +378,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth", @"api_key"]; + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -405,10 +407,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) -/// -/// @returns void +/// @param body Pet object that needs to be added to the store (optional) /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Pet not found", +/// code:405 message:"Validation exception" -(NSNumber*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -464,14 +467,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) -/// -/// @returns void +/// @param status Updated status of the pet (optional) /// +/// code:405 message:"Invalid input" -(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status @@ -548,14 +550,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) -/// -/// @returns void +/// @param file file to upload (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file @@ -628,5 +629,4 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h index 822701c3c41..3e101bed9a7 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h @@ -27,51 +27,39 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode; /// 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 -/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" -/// -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; - /// Returns pet inventories by status /// Returns a map of status codes to quantities /// -/// /// code:200 message:"successful operation" -/// /// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; - /// 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 -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" -/// /// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" -/// /// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m index e5964200f20..b86920b29e2 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m @@ -72,10 +72,10 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns void +/// @param orderId ID of the order that needs to be deleted /// +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" -(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set @@ -144,8 +144,8 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// @returns NSDictionary* -/// +/// code:200 message:"successful operation" +/// @return NSDictionary* -(NSNumber*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -200,10 +200,12 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 -/// -/// @returns SWGOrder* +/// @param orderId ID of pet that needs to be fetched /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid ID supplied", +/// code:404 message:"Order not found" +/// @return SWGOrder* -(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set @@ -272,10 +274,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) -/// -/// @returns SWGOrder* +/// @param body order placed for purchasing the pet (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid Order" +/// @return SWGOrder* -(NSNumber*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -329,5 +332,4 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h index 630f6679a81..f0b5e37550b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h @@ -27,99 +27,75 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// This can only be done by the logged in user. /// /// @param body Created user object (optional) -/// /// code:0 message:"successful operation" -/// -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; - /// Creates list of users with given input array /// /// /// @param body List of user object (optional) -/// /// code:0 message:"successful operation" -/// -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; - /// Creates list of users with given input array /// /// /// @param body List of user object (optional) -/// /// code:0 message:"successful operation" -/// -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; - /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted -/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" -/// -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; - /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" -/// /// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; - /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) -/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" -/// /// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; - /// Logs out current logged in user session /// /// -/// /// code:0 message:"successful operation" -/// -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; - /// 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 (optional) -/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" -/// -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m index 6ffb578ed76..df056030b75 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m @@ -72,10 +72,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) -/// -/// @returns void +/// @param body Created user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -131,10 +130,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) -/// -/// @returns void +/// @param body List of user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -190,10 +188,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) -/// -/// @returns void +/// @param body List of user object (optional) /// +/// code:0 message:"successful operation" -(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -249,10 +246,10 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted -/// -/// @returns void +/// @param username The name that needs to be deleted /// +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" -(NSNumber*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -321,10 +318,12 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. -/// -/// @returns SWGUser* +/// @param username The name that needs to be fetched. Use user1 for testing. /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username supplied", +/// code:404 message:"User not found" +/// @return SWGUser* -(NSNumber*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set @@ -393,12 +392,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) -/// -/// @returns NSString* +/// @param password The password for login in clear text (optional) /// +/// code:200 message:"successful operation", +/// code:400 message:"Invalid username/password supplied" +/// @return NSString* -(NSNumber*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { @@ -460,8 +460,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs out current logged in user session /// -/// @returns void -/// +/// code:0 message:"successful operation" -(NSNumber*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -516,12 +515,12 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) -/// -/// @returns void +/// @param body Updated user object (optional) /// +/// code:400 message:"Invalid user supplied", +/// code:404 message:"User not found" -(NSNumber*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { @@ -590,5 +589,4 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; } - @end diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index c4275413c62..9971ffff450 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -246,14 +246,14 @@ Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error cond ```objc SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; -// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; - // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; + NSNumber* petId = @789; // ID of pet that needs to be fetched @@ -283,7 +283,7 @@ Name | Type | Description | Notes ### Authorization -[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) +[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) ### HTTP request headers @@ -447,7 +447,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **petId** | **NSNumber***| ID of pet to update | **additionalMetadata** | **NSString***| Additional data to pass to server | [optional] - **file** | **NSURL*****NSURL***| file to upload | [optional] + **file** | **NSURL***| file to upload | [optional] ### Return type From 79fa53a4d83c9b4c367e97ba181af077bd205235 Mon Sep 17 00:00:00 2001 From: Greg Rashkevitch Date: Tue, 20 Dec 2016 20:22:43 +0200 Subject: [PATCH 197/269] Added Autodesk as a swagger codegen user --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 25d006bc879..851230f7ec5 100644 --- a/README.md +++ b/README.md @@ -754,6 +754,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Activehours](https://www.activehours.com/) - [Acunetix](https://www.acunetix.com/) - [Atlassian](https://www.atlassian.com/) +- [Autodesk](http://www.autodesk.com/) - [Avenida Compras S.A.](https://www.avenida.com.ar) - [AYLIEN](http://aylien.com/) - [Balance Internet](https://www.balanceinternet.com.au/) From d7afb22f1fcbb24b03dc3b2dab014877f2345d7a Mon Sep 17 00:00:00 2001 From: Michael Fulton Date: Tue, 20 Dec 2016 23:08:14 -0800 Subject: [PATCH 198/269] Fix Integer stub value defaulting to String in nodejs-server if format not specified (#4436) * check if property is a BaseIntegerProperty. This can occur when format is not specified in Swagger definition * Change coding style to be more consistent --- .../java/io/swagger/codegen/examples/ExampleGenerator.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java index 26a4422f071..bff78820b25 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/ExampleGenerator.java @@ -3,6 +3,7 @@ package io.swagger.codegen.examples; import io.swagger.models.Model; import io.swagger.models.ModelImpl; import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.BaseIntegerProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateTimeProperty; @@ -96,7 +97,7 @@ public class ExampleGenerator { return "2000-01-23"; } else if (property instanceof DateTimeProperty) { return "2000-01-23T04:56:07.000+00:00"; - } else if (property instanceof DecimalProperty) { + } else if (property instanceof DecimalProperty) { return new BigDecimal(1.3579); } else if (property instanceof DoubleProperty) { return 3.149; @@ -108,6 +109,9 @@ public class ExampleGenerator { return 123; } else if (property instanceof LongProperty) { return 123456789L; + // Properties that are not Integer or Long may still be BaseInteger + } else if (property instanceof BaseIntegerProperty) { + return 123; } else if (property instanceof MapProperty) { Map mp = new HashMap(); if (property.getName() != null) { From d52f5a3133596aecc2b26a3bfe433379fe8d3f7d Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 22 Dec 2016 21:11:34 +0800 Subject: [PATCH 199/269] update swagger pasrer to 1.0.25-SNAPSHOT --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b85e4885cb9..2dd1fd7bad8 100644 --- a/pom.xml +++ b/pom.xml @@ -850,7 +850,7 @@ - 1.0.24-SNAPSHOT + 1.0.25-SNAPSHOT 2.11.1 2.3.4 1.5.10 From e189388371745df1816f43318d0cda04ef41db9e Mon Sep 17 00:00:00 2001 From: Ezekiel Templin Date: Thu, 22 Dec 2016 05:37:12 -0800 Subject: [PATCH 200/269] [Ruby] Add Rakefile and Gemfile (#4448) * Add Rakefile, Gemfile, and update client generator * Update sample --- .../codegen/languages/RubyClientCodegen.java | 2 ++ .../src/main/resources/ruby/Gemfile.mustache | 7 +++++++ .../src/main/resources/ruby/Rakefile.mustache | 8 ++++++++ samples/client/petstore/ruby/Gemfile | 7 +++++-- samples/client/petstore/ruby/README.md | 2 +- samples/client/petstore/ruby/Rakefile | 13 +++++++------ samples/client/petstore/ruby/docs/FakeApi.md | 4 ++++ .../petstore/ruby/lib/petstore/api/fake_api.rb | 8 ++++---- 8 files changed, 38 insertions(+), 13 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/Gemfile.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/Rakefile.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 28122ae70a4..390a06335c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -250,6 +250,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + supportingFiles.add(new SupportingFile("Rakefile.mustache", "", "Rakefile")); + supportingFiles.add(new SupportingFile("Gemfile.mustache", "", "Gemfile")); // test files should not be overwritten writeOptional(outputFolder, new SupportingFile("rspec.mustache", "", ".rspec")); diff --git a/modules/swagger-codegen/src/main/resources/ruby/Gemfile.mustache b/modules/swagger-codegen/src/main/resources/ruby/Gemfile.mustache new file mode 100644 index 00000000000..d255a3ab238 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/Gemfile.mustache @@ -0,0 +1,7 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 12.0.0' +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/Rakefile.mustache b/modules/swagger-codegen/src/main/resources/ruby/Rakefile.mustache new file mode 100644 index 00000000000..d52c3e31753 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/Rakefile.mustache @@ -0,0 +1,8 @@ +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/client/petstore/ruby/Gemfile b/samples/client/petstore/ruby/Gemfile index 06d4a65272e..d255a3ab238 100644 --- a/samples/client/petstore/ruby/Gemfile +++ b/samples/client/petstore/ruby/Gemfile @@ -1,4 +1,7 @@ -source "http://rubygems.org" +source 'https://rubygems.org' -# Specify dependencies in swagger.gemspec gemspec + +group :development, :test do + gem 'rake', '~> 12.0.0' +end diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 090cbc360c9..2789989c589 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -8,7 +8,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build package: class io.swagger.codegen.languages.RubyClientCodegen +- Build package: io.swagger.codegen.languages.RubyClientCodegen ## Installation diff --git a/samples/client/petstore/ruby/Rakefile b/samples/client/petstore/ruby/Rakefile index e62140b1677..d52c3e31753 100644 --- a/samples/client/petstore/ruby/Rakefile +++ b/samples/client/petstore/ruby/Rakefile @@ -1,7 +1,8 @@ -require 'bundler' -Bundler::GemHelper.install_tasks +begin + require 'rspec/core/rake_task' -require 'rspec/core/rake_task' -require 'swagger' - -RSpec::Core::RakeTask.new('spec') \ No newline at end of file + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index aca0fbd10d6..6645e70f533 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -14,6 +14,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```ruby # load the gem @@ -142,6 +144,8 @@ nil (empty response body) To test enum parameters +To test enum parameters + ### Example ```ruby # load the gem diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index b869af1f445..403705d2746 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -20,7 +20,7 @@ module Petstore end # To test \"client\" model - # + # To test \"client\" model # @param body client model # @param [Hash] opts the optional parameters # @return [Client] @@ -30,7 +30,7 @@ module Petstore end # To test \"client\" model - # + # To test \"client\" model # @param body client model # @param [Hash] opts the optional parameters # @return [Array<(Client, Fixnum, Hash)>] Client data, response status code and response headers @@ -223,7 +223,7 @@ module Petstore end # To test enum parameters - # + # To test enum parameters # @param [Hash] opts the optional parameters # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) # @option opts [String] :enum_form_string Form parameter enum test (string) (default to -efg) @@ -240,7 +240,7 @@ module Petstore end # To test enum parameters - # + # To test enum parameters # @param [Hash] opts the optional parameters # @option opts [Array] :enum_form_string_array Form parameter enum test (string array) # @option opts [String] :enum_form_string Form parameter enum test (string) From 41701a15b03fe195b204cb4738ddf5d905159ca1 Mon Sep 17 00:00:00 2001 From: Anton Vasin Date: Thu, 22 Dec 2016 18:08:06 +0300 Subject: [PATCH 201/269] Fix typo. Creactor -> Creator (#4443) --- .../resources/TypeScript-Fetch/api.mustache | 4 +- .../typescript-fetch/builds/default/api.ts | 46 +++++++++---------- .../typescript-fetch/builds/es6-target/api.ts | 46 +++++++++---------- .../builds/with-npm-version/api.ts | 46 +++++++++---------- 4 files changed, 71 insertions(+), 71 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 16a41ff983b..54347410c56 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -63,7 +63,7 @@ export type {{{enumName}}} = {{#allowableValues}}{{#values}}"{{{.}}}"{{^-last}} * {{classname}} - fetch parameter creator{{#description}} * {{&description}}{{/description}} */ -export const {{classname}}FetchParamCreactor = { +export const {{classname}}FetchParamCreator = { {{#operation}} /** {{#summary}} * {{summary}}{{/summary}}{{#notes}} @@ -136,7 +136,7 @@ export const {{classname}}Fp = { * @param {{paramName}} {{description}}{{/allParams}} */ {{nickname}}({{#hasParams}}params: { {{#allParams}}"{{paramName}}"{{^required}}?{{/required}}: {{{dataType}}}; {{/allParams}} }, {{/hasParams}}options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}any{{/returnType}}> { - const fetchArgs = {{classname}}FetchParamCreactor.{{nickname}}({{#hasParams}}params, {{/hasParams}}options); + const fetchArgs = {{classname}}FetchParamCreator.{{nickname}}({{#hasParams}}params, {{/hasParams}}options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { diff --git a/samples/client/petstore/typescript-fetch/builds/default/api.ts b/samples/client/petstore/typescript-fetch/builds/default/api.ts index 917785c47da..1e821763c07 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/api.ts @@ -91,7 +91,7 @@ export interface User { /** * PetApi - fetch parameter creator */ -export const PetApiFetchParamCreactor = { +export const PetApiFetchParamCreator = { /** * Add a new pet to the store * @@ -305,7 +305,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); + const fetchArgs = PetApiFetchParamCreator.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -323,7 +323,7 @@ export const PetApiFp = { * @param apiKey */ deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); + const fetchArgs = PetApiFetchParamCreator.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -340,7 +340,7 @@ export const PetApiFp = { * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -357,7 +357,7 @@ export const PetApiFp = { * @param tags Tags to filter by */ findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -374,7 +374,7 @@ export const PetApiFp = { * @param petId ID of pet that needs to be fetched */ getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); + const fetchArgs = PetApiFetchParamCreator.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -391,7 +391,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -410,7 +410,7 @@ export const PetApiFp = { * @param status Updated status of the pet */ updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -429,7 +429,7 @@ export const PetApiFp = { * @param file file to upload */ uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); + const fetchArgs = PetApiFetchParamCreator.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -598,7 +598,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * StoreApi - fetch parameter creator */ -export const StoreApiFetchParamCreactor = { +export const StoreApiFetchParamCreator = { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -700,7 +700,7 @@ export const StoreApiFp = { * @param orderId ID of the order that needs to be deleted */ deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -716,7 +716,7 @@ export const StoreApiFp = { * Returns a map of status codes to quantities */ getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); + const fetchArgs = StoreApiFetchParamCreator.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -733,7 +733,7 @@ export const StoreApiFp = { * @param orderId ID of pet that needs to be fetched */ getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); + const fetchArgs = StoreApiFetchParamCreator.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -750,7 +750,7 @@ export const StoreApiFp = { * @param body order placed for purchasing the pet */ placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -843,7 +843,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * UserApi - fetch parameter creator */ -export const UserApiFetchParamCreactor = { +export const UserApiFetchParamCreator = { /** * Create user * This can only be done by the logged in user. @@ -1044,7 +1044,7 @@ export const UserApiFp = { * @param body Created user object */ createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); + const fetchArgs = UserApiFetchParamCreator.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1061,7 +1061,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1078,7 +1078,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1095,7 +1095,7 @@ export const UserApiFp = { * @param username The name that needs to be deleted */ deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); + const fetchArgs = UserApiFetchParamCreator.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1112,7 +1112,7 @@ export const UserApiFp = { * @param username The name that needs to be fetched. Use user1 for testing. */ getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); + const fetchArgs = UserApiFetchParamCreator.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1130,7 +1130,7 @@ export const UserApiFp = { * @param password The password for login in clear text */ loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); + const fetchArgs = UserApiFetchParamCreator.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1146,7 +1146,7 @@ export const UserApiFp = { * */ logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); + const fetchArgs = UserApiFetchParamCreator.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1164,7 +1164,7 @@ export const UserApiFp = { * @param body Updated user object */ updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); + const fetchArgs = UserApiFetchParamCreator.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts index 7bbbe76ca50..c5809c95808 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/api.ts @@ -90,7 +90,7 @@ export interface User { /** * PetApi - fetch parameter creator */ -export const PetApiFetchParamCreactor = { +export const PetApiFetchParamCreator = { /** * Add a new pet to the store * @@ -304,7 +304,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); + const fetchArgs = PetApiFetchParamCreator.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -322,7 +322,7 @@ export const PetApiFp = { * @param apiKey */ deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); + const fetchArgs = PetApiFetchParamCreator.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -339,7 +339,7 @@ export const PetApiFp = { * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -356,7 +356,7 @@ export const PetApiFp = { * @param tags Tags to filter by */ findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -373,7 +373,7 @@ export const PetApiFp = { * @param petId ID of pet that needs to be fetched */ getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); + const fetchArgs = PetApiFetchParamCreator.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -390,7 +390,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -409,7 +409,7 @@ export const PetApiFp = { * @param status Updated status of the pet */ updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -428,7 +428,7 @@ export const PetApiFp = { * @param file file to upload */ uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); + const fetchArgs = PetApiFetchParamCreator.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -597,7 +597,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * StoreApi - fetch parameter creator */ -export const StoreApiFetchParamCreactor = { +export const StoreApiFetchParamCreator = { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -699,7 +699,7 @@ export const StoreApiFp = { * @param orderId ID of the order that needs to be deleted */ deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -715,7 +715,7 @@ export const StoreApiFp = { * Returns a map of status codes to quantities */ getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); + const fetchArgs = StoreApiFetchParamCreator.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -732,7 +732,7 @@ export const StoreApiFp = { * @param orderId ID of pet that needs to be fetched */ getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); + const fetchArgs = StoreApiFetchParamCreator.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -749,7 +749,7 @@ export const StoreApiFp = { * @param body order placed for purchasing the pet */ placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -842,7 +842,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * UserApi - fetch parameter creator */ -export const UserApiFetchParamCreactor = { +export const UserApiFetchParamCreator = { /** * Create user * This can only be done by the logged in user. @@ -1043,7 +1043,7 @@ export const UserApiFp = { * @param body Created user object */ createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); + const fetchArgs = UserApiFetchParamCreator.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1060,7 +1060,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1077,7 +1077,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1094,7 +1094,7 @@ export const UserApiFp = { * @param username The name that needs to be deleted */ deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); + const fetchArgs = UserApiFetchParamCreator.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1111,7 +1111,7 @@ export const UserApiFp = { * @param username The name that needs to be fetched. Use user1 for testing. */ getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); + const fetchArgs = UserApiFetchParamCreator.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1129,7 +1129,7 @@ export const UserApiFp = { * @param password The password for login in clear text */ loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); + const fetchArgs = UserApiFetchParamCreator.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1145,7 +1145,7 @@ export const UserApiFp = { * */ logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); + const fetchArgs = UserApiFetchParamCreator.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1163,7 +1163,7 @@ export const UserApiFp = { * @param body Updated user object */ updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); + const fetchArgs = UserApiFetchParamCreator.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts index 917785c47da..1e821763c07 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/api.ts @@ -91,7 +91,7 @@ export interface User { /** * PetApi - fetch parameter creator */ -export const PetApiFetchParamCreactor = { +export const PetApiFetchParamCreator = { /** * Add a new pet to the store * @@ -305,7 +305,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ addPet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.addPet(params, options); + const fetchArgs = PetApiFetchParamCreator.addPet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -323,7 +323,7 @@ export const PetApiFp = { * @param apiKey */ deletePet(params: { "petId": number; "apiKey"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.deletePet(params, options); + const fetchArgs = PetApiFetchParamCreator.deletePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -340,7 +340,7 @@ export const PetApiFp = { * @param status Status values that need to be considered for filter */ findPetsByStatus(params: { "status"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByStatus(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByStatus(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -357,7 +357,7 @@ export const PetApiFp = { * @param tags Tags to filter by */ findPetsByTags(params: { "tags"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise> { - const fetchArgs = PetApiFetchParamCreactor.findPetsByTags(params, options); + const fetchArgs = PetApiFetchParamCreator.findPetsByTags(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -374,7 +374,7 @@ export const PetApiFp = { * @param petId ID of pet that needs to be fetched */ getPetById(params: { "petId": number; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.getPetById(params, options); + const fetchArgs = PetApiFetchParamCreator.getPetById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -391,7 +391,7 @@ export const PetApiFp = { * @param body Pet object that needs to be added to the store */ updatePet(params: { "body"?: Pet; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePet(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePet(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -410,7 +410,7 @@ export const PetApiFp = { * @param status Updated status of the pet */ updatePetWithForm(params: { "petId": string; "name"?: string; "status"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.updatePetWithForm(params, options); + const fetchArgs = PetApiFetchParamCreator.updatePetWithForm(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -429,7 +429,7 @@ export const PetApiFp = { * @param file file to upload */ uploadFile(params: { "petId": number; "additionalMetadata"?: string; "file"?: any; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = PetApiFetchParamCreactor.uploadFile(params, options); + const fetchArgs = PetApiFetchParamCreator.uploadFile(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -598,7 +598,7 @@ export const PetApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * StoreApi - fetch parameter creator */ -export const StoreApiFetchParamCreactor = { +export const StoreApiFetchParamCreator = { /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -700,7 +700,7 @@ export const StoreApiFp = { * @param orderId ID of the order that needs to be deleted */ deleteOrder(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.deleteOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.deleteOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -716,7 +716,7 @@ export const StoreApiFp = { * Returns a map of status codes to quantities */ getInventory(options?: any): (fetch: FetchAPI, basePath?: string) => Promise<{ [key: string]: number; }> { - const fetchArgs = StoreApiFetchParamCreactor.getInventory(options); + const fetchArgs = StoreApiFetchParamCreator.getInventory(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -733,7 +733,7 @@ export const StoreApiFp = { * @param orderId ID of pet that needs to be fetched */ getOrderById(params: { "orderId": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.getOrderById(params, options); + const fetchArgs = StoreApiFetchParamCreator.getOrderById(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -750,7 +750,7 @@ export const StoreApiFp = { * @param body order placed for purchasing the pet */ placeOrder(params: { "body"?: Order; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = StoreApiFetchParamCreactor.placeOrder(params, options); + const fetchArgs = StoreApiFetchParamCreator.placeOrder(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -843,7 +843,7 @@ export const StoreApiFactory = function (fetch?: FetchAPI, basePath?: string) { /** * UserApi - fetch parameter creator */ -export const UserApiFetchParamCreactor = { +export const UserApiFetchParamCreator = { /** * Create user * This can only be done by the logged in user. @@ -1044,7 +1044,7 @@ export const UserApiFp = { * @param body Created user object */ createUser(params: { "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUser(params, options); + const fetchArgs = UserApiFetchParamCreator.createUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1061,7 +1061,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithArrayInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithArrayInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithArrayInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1078,7 +1078,7 @@ export const UserApiFp = { * @param body List of user object */ createUsersWithListInput(params: { "body"?: Array; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.createUsersWithListInput(params, options); + const fetchArgs = UserApiFetchParamCreator.createUsersWithListInput(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1095,7 +1095,7 @@ export const UserApiFp = { * @param username The name that needs to be deleted */ deleteUser(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.deleteUser(params, options); + const fetchArgs = UserApiFetchParamCreator.deleteUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1112,7 +1112,7 @@ export const UserApiFp = { * @param username The name that needs to be fetched. Use user1 for testing. */ getUserByName(params: { "username": string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.getUserByName(params, options); + const fetchArgs = UserApiFetchParamCreator.getUserByName(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1130,7 +1130,7 @@ export const UserApiFp = { * @param password The password for login in clear text */ loginUser(params: { "username"?: string; "password"?: string; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.loginUser(params, options); + const fetchArgs = UserApiFetchParamCreator.loginUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1146,7 +1146,7 @@ export const UserApiFp = { * */ logoutUser(options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.logoutUser(options); + const fetchArgs = UserApiFetchParamCreator.logoutUser(options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { @@ -1164,7 +1164,7 @@ export const UserApiFp = { * @param body Updated user object */ updateUser(params: { "username": string; "body"?: User; }, options?: any): (fetch: FetchAPI, basePath?: string) => Promise { - const fetchArgs = UserApiFetchParamCreactor.updateUser(params, options); + const fetchArgs = UserApiFetchParamCreator.updateUser(params, options); return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { if (response.status >= 200 && response.status < 300) { From 27f1b6ee988767129ed2696e204f0c80f3d13adc Mon Sep 17 00:00:00 2001 From: Jun Mukai Date: Thu, 22 Dec 2016 07:11:52 -0800 Subject: [PATCH 202/269] Introduce NodeJS codegen for Google Cloud Functions. (#4406) * Another approach: extending NodeJS server to support GCF. This does not add a new language, but adding some client options to support Google Cloud Functions (GCF). * Add URLs for how to deploy the generated code. Adds the client options help message and the README.md file. --- bin/nodejs-petstore-google-cloud-functions.sh | 31 + .../languages/NodeJSServerCodegen.java | 108 ++- .../index.mustache | 44 ++ .../src/main/resources/nodejs/README.mustache | 8 + .../main/resources/nodejs/index-gcf.mustache | 44 ++ .../main/resources/nodejs/package.mustache | 6 +- .../nodejs/NodeJSServerOptionsTest.java | 2 + .../options/NodeJSServerOptionsProvider.java | 6 +- .../nodejs-google-cloud-functions/README.md | 11 + .../api/swagger.yaml | 734 ++++++++++++++++++ .../controllers/Pet.js | 39 + .../controllers/PetService.js | 154 ++++ .../controllers/Store.js | 23 + .../controllers/StoreService.js | 77 ++ .../controllers/User.js | 39 + .../controllers/UserService.js | 100 +++ .../nodejs-google-cloud-functions/index.js | 44 ++ .../package.json | 15 + 18 files changed, 1462 insertions(+), 23 deletions(-) create mode 100755 bin/nodejs-petstore-google-cloud-functions.sh create mode 100644 modules/swagger-codegen/src/main/resources/nodejs-google-cloud-functions/index.mustache create mode 100644 modules/swagger-codegen/src/main/resources/nodejs/index-gcf.mustache create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/README.md create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/api/swagger.yaml create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/Pet.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/PetService.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/Store.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/StoreService.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/User.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/controllers/UserService.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/index.js create mode 100644 samples/server/petstore/nodejs-google-cloud-functions/package.json diff --git a/bin/nodejs-petstore-google-cloud-functions.sh b/bin/nodejs-petstore-google-cloud-functions.sh new file mode 100755 index 00000000000..f5df577b481 --- /dev/null +++ b/bin/nodejs-petstore-google-cloud-functions.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.yaml -l nodejs-server --additional-properties=googleCloudFunctions=true -o samples/server/petstore/nodejs-google-cloud-functions" + +java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index b9ab1b00f8b..87e44d23632 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -24,10 +24,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig private static final Logger LOGGER = LoggerFactory.getLogger(NodeJSServerCodegen.class); + public static final String GOOGLE_CLOUD_FUNCTIONS = "googleCloudFunctions"; + public static final String EXPORTED_NAME = "exportedName"; + protected String apiVersion = "1.0.0"; protected int serverPort = 8080; protected String projectName = "swagger-server"; + protected boolean googleCloudFunctions; + protected String exportedName; + public NodeJSServerCodegen() { super(); @@ -76,27 +82,15 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put("apiVersion", apiVersion); additionalProperties.put("serverPort", serverPort); - /* - * Supporting Files. You can write single files for the generator with the - * entire object tree available. If the input file has a suffix of `.mustache - * it will be processed by the template engine. Otherwise, it will be copied - */ - // supportingFiles.add(new SupportingFile("controller.mustache", - // "controllers", - // "controller.js") - // ); - supportingFiles.add(new SupportingFile("swagger.mustache", - "api", - "swagger.yaml") - ); - writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js")); - writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json")); - writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); - if (System.getProperty("noservice") == null) { - apiTemplateFiles.put( - "service.mustache", // the template to use - "Service.js"); // the extension for each file to write - } + cliOptions.add(CliOption.newBoolean(GOOGLE_CLOUD_FUNCTIONS, + "When specified, it will generate the code which runs within Google Cloud Functions " + + "instead of standalone Node.JS server. See " + + "https://cloud.google.com/functions/docs/quickstart for the details of how to " + + "deploy the generated code.")); + cliOptions.add(new CliOption(EXPORTED_NAME, + "When the generated code will be deployed to Google Cloud Functions, this option can be " + + "used to update the name of the exported function. By default, it refers to the " + + "basePath. This does not affect normal standalone nodejs server code.")); } @Override @@ -171,6 +165,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); } + public boolean getGoogleCloudFunctions() { + return googleCloudFunctions; + } + + public void setGoogleCloudFunctions(boolean value) { + googleCloudFunctions = value; + } + + public String getExportedName() { + return exportedName; + } + + public void setExportedName(String name) { + exportedName = name; + } + @Override public Map postProcessOperations(Map objs) { @SuppressWarnings("unchecked") @@ -240,6 +250,46 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig return opsByPathList; } + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey(GOOGLE_CLOUD_FUNCTIONS)) { + setGoogleCloudFunctions( + Boolean.valueOf(additionalProperties.get(GOOGLE_CLOUD_FUNCTIONS).toString())); + } + + if (additionalProperties.containsKey(EXPORTED_NAME)) { + setExportedName((String)additionalProperties.get(EXPORTED_NAME)); + } + + /* + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + // supportingFiles.add(new SupportingFile("controller.mustache", + // "controllers", + // "controller.js") + // ); + supportingFiles.add(new SupportingFile("swagger.mustache", + "api", + "swagger.yaml") + ); + if (getGoogleCloudFunctions()) { + writeOptional(outputFolder, new SupportingFile("index-gcf.mustache", "", "index.js")); + } else { + writeOptional(outputFolder, new SupportingFile("index.mustache", "", "index.js")); + } + writeOptional(outputFolder, new SupportingFile("package.mustache", "", "package.json")); + writeOptional(outputFolder, new SupportingFile("README.mustache", "", "README.md")); + if (System.getProperty("noservice") == null) { + apiTemplateFiles.put( + "service.mustache", // the template to use + "Service.js"); // the extension for each file to write + } + } + @Override public void preprocessSwagger(Swagger swagger) { String host = swagger.getHost(); @@ -262,6 +312,22 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } } + if (getGoogleCloudFunctions()) { + // Note that Cloud Functions don't allow customizing port name, simply checking host + // is good enough. + if (!host.endsWith(".cloudfunctions.net")) { + LOGGER.warn("Host " + host + " seems not matching with cloudfunctions.net URL."); + } + if (!additionalProperties.containsKey(EXPORTED_NAME)) { + String basePath = swagger.getBasePath(); + if (basePath == null || basePath.equals("/")) { + LOGGER.warn("Cannot find the exported name properly. Using 'openapi' as the exported name"); + basePath = "/openapi"; + } + additionalProperties.put(EXPORTED_NAME, basePath.substring(1)); + } + } + // need vendor extensions for x-swagger-router-controller Map paths = swagger.getPaths(); if(paths != null) { diff --git a/modules/swagger-codegen/src/main/resources/nodejs-google-cloud-functions/index.mustache b/modules/swagger-codegen/src/main/resources/nodejs-google-cloud-functions/index.mustache new file mode 100644 index 00000000000..b406ff7f140 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs-google-cloud-functions/index.mustache @@ -0,0 +1,44 @@ +'use strict'; + +var swaggerTools = require('swagger-tools'); +var jsyaml = require('js-yaml'); +var fs = require('fs'); + +// swaggerRouter configuration +var options = { + controllers: './controllers', + useStubs: false +}; + +// The Swagger document (require it, build it programmatically, fetch it from a URL, ...) +var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var swaggerDoc = jsyaml.safeLoad(spec); + +function toPromise(f, req, res) { + return new Promise(function(resolve, reject) { + f(req, res, function(err) { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +} + +exports.{{exportedName}} = function(req, res) { + swaggerTools.initializeMiddleware(swaggerDoc, function(middleware) { + var metadata = middleware.swaggerMetadata(); + var validator = middleware.swaggerValidator(); + var router = middleware.swaggerRouter(options); + req.url = swaggerDoc.basePath + req.url; + toPromise(metadata, req, res).then(function() { + return toPromise(validator, req, res); + }).then(function() { + return toPromise(router, req, res); + }).catch(function(err) { + console.error(err); + res.status(res.statusCode || 400).send(err); + }); + }); +}; diff --git a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache index b8fd4cd80ab..b7df8abcd3e 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache @@ -3,6 +3,7 @@ ## Overview This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +{{^googleCloudFunctions}} ### Running the server To run the server, run: @@ -15,5 +16,12 @@ To view the Swagger UI interface: ``` open http://localhost:{{serverPort}}/docs ``` +{{/googleCloudFunctions}} +{{#googleCloudFunctions}} +### Deploying the function +To deploy this module into Google Cloud Functions, you will have to use Google Cloud SDK commandline tool. + +See [Google Cloud Functions quick start guide](https://cloud.google.com/functions/docs/quickstart) and [Deploying Cloud Functions](https://cloud.google.com/functions/docs/deploying/) for the details. +{{/googleCloudFunctions}} This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. diff --git a/modules/swagger-codegen/src/main/resources/nodejs/index-gcf.mustache b/modules/swagger-codegen/src/main/resources/nodejs/index-gcf.mustache new file mode 100644 index 00000000000..b406ff7f140 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/index-gcf.mustache @@ -0,0 +1,44 @@ +'use strict'; + +var swaggerTools = require('swagger-tools'); +var jsyaml = require('js-yaml'); +var fs = require('fs'); + +// swaggerRouter configuration +var options = { + controllers: './controllers', + useStubs: false +}; + +// The Swagger document (require it, build it programmatically, fetch it from a URL, ...) +var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var swaggerDoc = jsyaml.safeLoad(spec); + +function toPromise(f, req, res) { + return new Promise(function(resolve, reject) { + f(req, res, function(err) { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +} + +exports.{{exportedName}} = function(req, res) { + swaggerTools.initializeMiddleware(swaggerDoc, function(middleware) { + var metadata = middleware.swaggerMetadata(); + var validator = middleware.swaggerValidator(); + var router = middleware.swaggerRouter(options); + req.url = swaggerDoc.basePath + req.url; + toPromise(metadata, req, res).then(function() { + return toPromise(validator, req, res); + }).then(function() { + return toPromise(router, req, res); + }).catch(function(err) { + console.error(err); + res.status(res.statusCode || 400).send(err); + }); + }); +}; diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 4e59cfb3c2a..ed296f865c2 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -3,17 +3,21 @@ "version": "{{appVersion}}", "description": "{{{appDescription}}}", "main": "index.js", + {{^googleCloudFunctions}} "scripts": { "prestart": "npm install", "start": "node index.js" - }, + }, + {{/googleCloudFunctions}} "keywords": [ "swagger" ], "license": "Unlicense", "private": true, "dependencies": { + {{^googleCloudFunctions}} "connect": "^3.2.0", + {{/googleCloudFunctions}} "js-yaml": "^3.3.0", "swagger-tools": "0.10.1" } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java index c1cfa43b08b..a1cc4aab2b9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -27,6 +27,8 @@ public class NodeJSServerOptionsTest extends AbstractOptionsTest { protected void setExpectations() { new Expectations(clientCodegen) {{ clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(NodeJSServerOptionsProvider.SORT_PARAMS_VALUE)); + clientCodegen.setGoogleCloudFunctions(Boolean.valueOf(NodeJSServerOptionsProvider.GOOGLE_CLOUD_FUNCTIONS)); + clientCodegen.setExportedName(NodeJSServerOptionsProvider.EXPORTED_NAME); times = 1; }}; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java index 6252bbd08fc..e18704e2b54 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java @@ -1,7 +1,7 @@ package io.swagger.codegen.options; import io.swagger.codegen.CodegenConstants; - +import io.swagger.codegen.languages.NodeJSServerCodegen; import com.google.common.collect.ImmutableMap; import java.util.Map; @@ -9,6 +9,8 @@ import java.util.Map; public class NodeJSServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String GOOGLE_CLOUD_FUNCTIONS = "false"; + public static final String EXPORTED_NAME = "exported"; @Override public String getLanguage() { @@ -20,6 +22,8 @@ public class NodeJSServerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(NodeJSServerCodegen.GOOGLE_CLOUD_FUNCTIONS, GOOGLE_CLOUD_FUNCTIONS) + .put(NodeJSServerCodegen.EXPORTED_NAME, EXPORTED_NAME) .build(); } diff --git a/samples/server/petstore/nodejs-google-cloud-functions/README.md b/samples/server/petstore/nodejs-google-cloud-functions/README.md new file mode 100644 index 00000000000..44270f0a198 --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/README.md @@ -0,0 +1,11 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. + +### Deploying the function +To deploy this module into Google Cloud Functions, you will have to use Google Cloud SDK commandline tool. + +See [Google Cloud Functions quick start guide](https://cloud.google.com/functions/docs/quickstart) and [Deploying Cloud Functions](https://cloud.google.com/functions/docs/deploying/) for the details. + +This project leverages the mega-awesome [swagger-tools](https://github.com/apigee-127/swagger-tools) middleware which does most all the work. diff --git a/samples/server/petstore/nodejs-google-cloud-functions/api/swagger.yaml b/samples/server/petstore/nodejs-google-cloud-functions/api/swagger.yaml new file mode 100644 index 00000000000..b47e700ae1f --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/api/swagger.yaml @@ -0,0 +1,734 @@ +--- +swagger: "2.0" +info: + description: "This is a sample server Petstore server. You can find out more about\ + \ Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/).\ + \ For this sample, you can use the api key `special-key` to test the authorization\ + \ filters." + version: "1.0.0" + title: "Swagger Petstore" + termsOfService: "http://swagger.io/terms/" + contact: + email: "apiteam@swagger.io" + license: + name: "Apache 2.0" + url: "http://www.apache.org/licenses/LICENSE-2.0.html" +host: "petstore.swagger.io" +basePath: "/v2" +tags: +- name: "pet" + description: "Everything about your Pets" + externalDocs: + description: "Find out more" + url: "http://swagger.io" +- name: "store" + description: "Access to Petstore orders" +- name: "user" + description: "Operations about user" + externalDocs: + description: "Find out more about our store" + url: "http://swagger.io" +schemes: +- "http" +paths: + /pet: + post: + tags: + - "pet" + summary: "Add a new pet to the store" + description: "" + operationId: "addPet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + put: + tags: + - "pet" + summary: "Update an existing pet" + description: "" + operationId: "updatePet" + consumes: + - "application/json" + - "application/xml" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Pet object that needs to be added to the store" + required: true + schema: + $ref: "#/definitions/Pet" + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + 405: + description: "Validation exception" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + /pet/findByStatus: + get: + tags: + - "pet" + summary: "Finds Pets by status" + description: "Multiple status values can be provided with comma separated strings" + operationId: "findPetsByStatus" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "status" + in: "query" + description: "Status values that need to be considered for filter" + required: true + type: "array" + items: + type: "string" + default: "available" + enum: + - "available" + - "pending" + - "sold" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid status value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + /pet/findByTags: + get: + tags: + - "pet" + summary: "Finds Pets by tags" + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: "findPetsByTags" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "tags" + in: "query" + description: "Tags to filter by" + required: true + type: "array" + items: + type: "string" + collectionFormat: "csv" + responses: + 200: + description: "successful operation" + schema: + type: "array" + items: + $ref: "#/definitions/Pet" + 400: + description: "Invalid tag value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + /pet/{petId}: + get: + tags: + - "pet" + summary: "Find pet by ID" + description: "Returns a single pet" + operationId: "getPetById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to return" + required: true + type: "integer" + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Pet" + 400: + description: "Invalid ID supplied" + 404: + description: "Pet not found" + security: + - api_key: [] + x-swagger-router-controller: "Pet" + post: + tags: + - "pet" + summary: "Updates a pet in the store with form data" + description: "" + operationId: "updatePetWithForm" + consumes: + - "application/x-www-form-urlencoded" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet that needs to be updated" + required: true + type: "integer" + format: "int64" + - name: "name" + in: "formData" + description: "Updated name of the pet" + required: false + type: "string" + - name: "status" + in: "formData" + description: "Updated status of the pet" + required: false + type: "string" + responses: + 405: + description: "Invalid input" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + delete: + tags: + - "pet" + summary: "Deletes a pet" + description: "" + operationId: "deletePet" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "api_key" + in: "header" + required: false + type: "string" + - name: "petId" + in: "path" + description: "Pet id to delete" + required: true + type: "integer" + format: "int64" + responses: + 400: + description: "Invalid pet value" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + /pet/{petId}/uploadImage: + post: + tags: + - "pet" + summary: "uploads an image" + description: "" + operationId: "uploadFile" + consumes: + - "multipart/form-data" + produces: + - "application/json" + parameters: + - name: "petId" + in: "path" + description: "ID of pet to update" + required: true + type: "integer" + format: "int64" + - name: "additionalMetadata" + in: "formData" + description: "Additional data to pass to server" + required: false + type: "string" + - name: "file" + in: "formData" + description: "file to upload" + required: false + type: "file" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/ApiResponse" + security: + - petstore_auth: + - "write:pets" + - "read:pets" + x-swagger-router-controller: "Pet" + /store/inventory: + get: + tags: + - "store" + summary: "Returns pet inventories by status" + description: "Returns a map of status codes to quantities" + operationId: "getInventory" + produces: + - "application/json" + parameters: [] + responses: + 200: + description: "successful operation" + schema: + type: "object" + additionalProperties: + type: "integer" + format: "int32" + security: + - api_key: [] + x-swagger-router-controller: "Store" + /store/order: + post: + tags: + - "store" + summary: "Place an order for a pet" + description: "" + operationId: "placeOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "order placed for purchasing the pet" + required: true + schema: + $ref: "#/definitions/Order" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid Order" + x-swagger-router-controller: "Store" + /store/order/{orderId}: + get: + tags: + - "store" + summary: "Find purchase order by ID" + description: "For valid response try integer IDs with value <= 5 or > 10. Other\ + \ values will generated exceptions" + operationId: "getOrderById" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of pet that needs to be fetched" + required: true + type: "integer" + maximum: 5 + minimum: 1 + format: "int64" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/Order" + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-swagger-router-controller: "Store" + delete: + tags: + - "store" + summary: "Delete purchase order by ID" + description: "For valid response try integer IDs with value < 1000. Anything\ + \ above 1000 or nonintegers will generate API errors" + operationId: "deleteOrder" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "orderId" + in: "path" + description: "ID of the order that needs to be deleted" + required: true + type: "string" + minimum: 1 + responses: + 400: + description: "Invalid ID supplied" + 404: + description: "Order not found" + x-swagger-router-controller: "Store" + /user: + post: + tags: + - "user" + summary: "Create user" + description: "This can only be done by the logged in user." + operationId: "createUser" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "Created user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-swagger-router-controller: "User" + /user/createWithArray: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithArrayInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-swagger-router-controller: "User" + /user/createWithList: + post: + tags: + - "user" + summary: "Creates list of users with given input array" + description: "" + operationId: "createUsersWithListInput" + produces: + - "application/xml" + - "application/json" + parameters: + - in: "body" + name: "body" + description: "List of user object" + required: true + schema: + type: "array" + items: + $ref: "#/definitions/User" + responses: + default: + description: "successful operation" + x-swagger-router-controller: "User" + /user/login: + get: + tags: + - "user" + summary: "Logs user into the system" + description: "" + operationId: "loginUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "query" + description: "The user name for login" + required: true + type: "string" + - name: "password" + in: "query" + description: "The password for login in clear text" + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + type: "string" + headers: + X-Rate-Limit: + type: "integer" + format: "int32" + description: "calls per hour allowed by the user" + X-Expires-After: + type: "string" + format: "date-time" + description: "date in UTC when toekn expires" + 400: + description: "Invalid username/password supplied" + x-swagger-router-controller: "User" + /user/logout: + get: + tags: + - "user" + summary: "Logs out current logged in user session" + description: "" + operationId: "logoutUser" + produces: + - "application/xml" + - "application/json" + parameters: [] + responses: + default: + description: "successful operation" + x-swagger-router-controller: "User" + /user/{username}: + get: + tags: + - "user" + summary: "Get user by user name" + description: "" + operationId: "getUserByName" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be fetched. Use user1 for testing. " + required: true + type: "string" + responses: + 200: + description: "successful operation" + schema: + $ref: "#/definitions/User" + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-swagger-router-controller: "User" + put: + tags: + - "user" + summary: "Updated user" + description: "This can only be done by the logged in user." + operationId: "updateUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "name that need to be deleted" + required: true + type: "string" + - in: "body" + name: "body" + description: "Updated user object" + required: true + schema: + $ref: "#/definitions/User" + responses: + 400: + description: "Invalid user supplied" + 404: + description: "User not found" + x-swagger-router-controller: "User" + delete: + tags: + - "user" + summary: "Delete user" + description: "This can only be done by the logged in user." + operationId: "deleteUser" + produces: + - "application/xml" + - "application/json" + parameters: + - name: "username" + in: "path" + description: "The name that needs to be deleted" + required: true + type: "string" + responses: + 400: + description: "Invalid username supplied" + 404: + description: "User not found" + x-swagger-router-controller: "User" +securityDefinitions: + petstore_auth: + type: "oauth2" + authorizationUrl: "http://petstore.swagger.io/api/oauth/dialog" + flow: "implicit" + scopes: + write:pets: "modify pets in your account" + read:pets: "read your pets" + api_key: + type: "apiKey" + name: "api_key" + in: "header" +definitions: + Order: + type: "object" + properties: + id: + type: "integer" + format: "int64" + petId: + type: "integer" + format: "int64" + quantity: + type: "integer" + format: "int32" + shipDate: + type: "string" + format: "date-time" + status: + type: "string" + description: "Order Status" + enum: + - "placed" + - "approved" + - "delivered" + complete: + type: "boolean" + default: false + title: "Pet Order" + description: "An order for a pets from the pet store" + xml: + name: "Order" + Category: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet catehgry" + description: "A category for a pet" + xml: + name: "Category" + User: + type: "object" + properties: + id: + type: "integer" + format: "int64" + username: + type: "string" + firstName: + type: "string" + lastName: + type: "string" + email: + type: "string" + password: + type: "string" + phone: + type: "string" + userStatus: + type: "integer" + format: "int32" + description: "User Status" + title: "a User" + description: "A User who is purchasing from the pet store" + xml: + name: "User" + Tag: + type: "object" + properties: + id: + type: "integer" + format: "int64" + name: + type: "string" + title: "Pet Tag" + description: "A tag for a pet" + xml: + name: "Tag" + Pet: + type: "object" + required: + - "name" + - "photoUrls" + properties: + id: + type: "integer" + format: "int64" + category: + $ref: "#/definitions/Category" + name: + type: "string" + example: "doggie" + photoUrls: + type: "array" + xml: + name: "photoUrl" + wrapped: true + items: + type: "string" + tags: + type: "array" + xml: + name: "tag" + wrapped: true + items: + $ref: "#/definitions/Tag" + status: + type: "string" + description: "pet status in the store" + enum: + - "available" + - "pending" + - "sold" + title: "a Pet" + description: "A pet for sale in the pet store" + xml: + name: "Pet" + ApiResponse: + type: "object" + properties: + code: + type: "integer" + format: "int32" + type: + type: "string" + message: + type: "string" + title: "An uploaded response" + description: "Describes the result of uploading an image resource" +externalDocs: + description: "Find out more about Swagger" + url: "http://swagger.io" diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/Pet.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/Pet.js new file mode 100644 index 00000000000..3748305bfbe --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/Pet.js @@ -0,0 +1,39 @@ +'use strict'; + +var url = require('url'); + + +var Pet = require('./PetService'); + + +module.exports.addPet = function addPet (req, res, next) { + Pet.addPet(req.swagger.params, res, next); +}; + +module.exports.deletePet = function deletePet (req, res, next) { + Pet.deletePet(req.swagger.params, res, next); +}; + +module.exports.findPetsByStatus = function findPetsByStatus (req, res, next) { + Pet.findPetsByStatus(req.swagger.params, res, next); +}; + +module.exports.findPetsByTags = function findPetsByTags (req, res, next) { + Pet.findPetsByTags(req.swagger.params, res, next); +}; + +module.exports.getPetById = function getPetById (req, res, next) { + Pet.getPetById(req.swagger.params, res, next); +}; + +module.exports.updatePet = function updatePet (req, res, next) { + Pet.updatePet(req.swagger.params, res, next); +}; + +module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { + Pet.updatePetWithForm(req.swagger.params, res, next); +}; + +module.exports.uploadFile = function uploadFile (req, res, next) { + Pet.uploadFile(req.swagger.params, res, next); +}; diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/PetService.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/PetService.js new file mode 100644 index 00000000000..c8da68c1519 --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/PetService.js @@ -0,0 +1,154 @@ +'use strict'; + +exports.addPet = function(args, res, next) { + /** + * parameters expected in the args: + * body (Pet) + **/ + // no response value expected for this operation + res.end(); +} + +exports.deletePet = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + * api_key (String) + **/ + // no response value expected for this operation + res.end(); +} + +exports.findPetsByStatus = function(args, res, next) { + /** + * parameters expected in the args: + * status (List) + **/ + var examples = {}; + examples['application/json'] = [ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.findPetsByTags = function(args, res, next) { + /** + * parameters expected in the args: + * tags (List) + **/ + var examples = {}; + examples['application/json'] = [ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.getPetById = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + **/ + var examples = {}; + examples['application/json'] = { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", + "id" : 123456789, + "category" : { + "name" : "aeiou", + "id" : 123456789 + }, + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.updatePet = function(args, res, next) { + /** + * parameters expected in the args: + * body (Pet) + **/ + // no response value expected for this operation + res.end(); +} + +exports.updatePetWithForm = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + * name (String) + * status (String) + **/ + // no response value expected for this operation + res.end(); +} + +exports.uploadFile = function(args, res, next) { + /** + * parameters expected in the args: + * petId (Long) + * additionalMetadata (String) + * file (File) + **/ + var examples = {}; + examples['application/json'] = { + "code" : 123, + "type" : "aeiou", + "message" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/Store.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/Store.js new file mode 100644 index 00000000000..ac67c740d29 --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/Store.js @@ -0,0 +1,23 @@ +'use strict'; + +var url = require('url'); + + +var Store = require('./StoreService'); + + +module.exports.deleteOrder = function deleteOrder (req, res, next) { + Store.deleteOrder(req.swagger.params, res, next); +}; + +module.exports.getInventory = function getInventory (req, res, next) { + Store.getInventory(req.swagger.params, res, next); +}; + +module.exports.getOrderById = function getOrderById (req, res, next) { + Store.getOrderById(req.swagger.params, res, next); +}; + +module.exports.placeOrder = function placeOrder (req, res, next) { + Store.placeOrder(req.swagger.params, res, next); +}; diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/StoreService.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/StoreService.js new file mode 100644 index 00000000000..aed5113a915 --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/StoreService.js @@ -0,0 +1,77 @@ +'use strict'; + +exports.deleteOrder = function(args, res, next) { + /** + * parameters expected in the args: + * orderId (String) + **/ + // no response value expected for this operation + res.end(); +} + +exports.getInventory = function(args, res, next) { + /** + * parameters expected in the args: + **/ + var examples = {}; + examples['application/json'] = { + "key" : 123 +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.getOrderById = function(args, res, next) { + /** + * parameters expected in the args: + * orderId (Long) + **/ + var examples = {}; + examples['application/json'] = { + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.placeOrder = function(args, res, next) { + /** + * parameters expected in the args: + * body (Order) + **/ + var examples = {}; + examples['application/json'] = { + "petId" : 123456789, + "quantity" : 123, + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/User.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/User.js new file mode 100644 index 00000000000..bac1d7f6a88 --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/User.js @@ -0,0 +1,39 @@ +'use strict'; + +var url = require('url'); + + +var User = require('./UserService'); + + +module.exports.createUser = function createUser (req, res, next) { + User.createUser(req.swagger.params, res, next); +}; + +module.exports.createUsersWithArrayInput = function createUsersWithArrayInput (req, res, next) { + User.createUsersWithArrayInput(req.swagger.params, res, next); +}; + +module.exports.createUsersWithListInput = function createUsersWithListInput (req, res, next) { + User.createUsersWithListInput(req.swagger.params, res, next); +}; + +module.exports.deleteUser = function deleteUser (req, res, next) { + User.deleteUser(req.swagger.params, res, next); +}; + +module.exports.getUserByName = function getUserByName (req, res, next) { + User.getUserByName(req.swagger.params, res, next); +}; + +module.exports.loginUser = function loginUser (req, res, next) { + User.loginUser(req.swagger.params, res, next); +}; + +module.exports.logoutUser = function logoutUser (req, res, next) { + User.logoutUser(req.swagger.params, res, next); +}; + +module.exports.updateUser = function updateUser (req, res, next) { + User.updateUser(req.swagger.params, res, next); +}; diff --git a/samples/server/petstore/nodejs-google-cloud-functions/controllers/UserService.js b/samples/server/petstore/nodejs-google-cloud-functions/controllers/UserService.js new file mode 100644 index 00000000000..3a62feeaf3f --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/controllers/UserService.js @@ -0,0 +1,100 @@ +'use strict'; + +exports.createUser = function(args, res, next) { + /** + * parameters expected in the args: + * body (User) + **/ + // no response value expected for this operation + res.end(); +} + +exports.createUsersWithArrayInput = function(args, res, next) { + /** + * parameters expected in the args: + * body (List) + **/ + // no response value expected for this operation + res.end(); +} + +exports.createUsersWithListInput = function(args, res, next) { + /** + * parameters expected in the args: + * body (List) + **/ + // no response value expected for this operation + res.end(); +} + +exports.deleteUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + **/ + // no response value expected for this operation + res.end(); +} + +exports.getUserByName = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + **/ + var examples = {}; + examples['application/json'] = { + "firstName" : "aeiou", + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.loginUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * password (String) + **/ + var examples = {}; + examples['application/json'] = "aeiou"; + if(Object.keys(examples).length > 0) { + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); + } + else { + res.end(); + } + +} + +exports.logoutUser = function(args, res, next) { + /** + * parameters expected in the args: + **/ + // no response value expected for this operation + res.end(); +} + +exports.updateUser = function(args, res, next) { + /** + * parameters expected in the args: + * username (String) + * body (User) + **/ + // no response value expected for this operation + res.end(); +} + diff --git a/samples/server/petstore/nodejs-google-cloud-functions/index.js b/samples/server/petstore/nodejs-google-cloud-functions/index.js new file mode 100644 index 00000000000..7c4cf42a3be --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/index.js @@ -0,0 +1,44 @@ +'use strict'; + +var swaggerTools = require('swagger-tools'); +var jsyaml = require('js-yaml'); +var fs = require('fs'); + +// swaggerRouter configuration +var options = { + controllers: './controllers', + useStubs: false +}; + +// The Swagger document (require it, build it programmatically, fetch it from a URL, ...) +var spec = fs.readFileSync('./api/swagger.yaml', 'utf8'); +var swaggerDoc = jsyaml.safeLoad(spec); + +function toPromise(f, req, res) { + return new Promise(function(resolve, reject) { + f(req, res, function(err) { + if (err) { + reject(err); + } else { + resolve(); + } + }); + }); +} + +exports.v2 = function(req, res) { + swaggerTools.initializeMiddleware(swaggerDoc, function(middleware) { + var metadata = middleware.swaggerMetadata(); + var validator = middleware.swaggerValidator(); + var router = middleware.swaggerRouter(options); + req.url = swaggerDoc.basePath + req.url; + toPromise(metadata, req, res).then(function() { + return toPromise(validator, req, res); + }).then(function() { + return toPromise(router, req, res); + }).catch(function(err) { + console.error(err); + res.status(res.statusCode || 400).send(err); + }); + }); +}; diff --git a/samples/server/petstore/nodejs-google-cloud-functions/package.json b/samples/server/petstore/nodejs-google-cloud-functions/package.json new file mode 100644 index 00000000000..5008aba1acd --- /dev/null +++ b/samples/server/petstore/nodejs-google-cloud-functions/package.json @@ -0,0 +1,15 @@ +{ + "name": "swagger-petstore", + "version": "1.0.0", + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "main": "index.js", + "keywords": [ + "swagger" + ], + "license": "Unlicense", + "private": true, + "dependencies": { + "js-yaml": "^3.3.0", + "swagger-tools": "0.10.1" + } +} From aed21bba733bcabeeda0e05331a24e32ec1edc4f Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 23 Dec 2016 02:05:10 +0800 Subject: [PATCH 203/269] better code format for nodejs server (#4411) --- .../main/resources/nodejs/controller.mustache | 4 +- .../main/resources/nodejs/service.mustache | 34 +++-- .../server/petstore/nodejs/controllers/Pet.js | 2 - .../petstore/nodejs/controllers/PetService.js | 118 ++++++++++-------- .../petstore/nodejs/controllers/Store.js | 2 - .../nodejs/controllers/StoreService.js | 59 +++++---- .../petstore/nodejs/controllers/User.js | 2 - .../nodejs/controllers/UserService.js | 96 ++++++++------ samples/server/petstore/nodejs/package.json | 2 +- 9 files changed, 178 insertions(+), 141 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache index 0f0c35bc0ee..f94fe89ef7e 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/controller.mustache @@ -1,15 +1,13 @@ 'use strict'; var url = require('url'); - {{#operations}} var {{classname}} = require('./{{classname}}Service'); - {{#operation}} module.exports.{{nickname}} = function {{nickname}} (req, res, next) { {{classname}}.{{nickname}}(req.swagger.params, res, next); }; {{/operation}} -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache index c018e9ae294..e5a44836e07 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/service.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/service.mustache @@ -2,26 +2,40 @@ {{#operations}} {{#operation}} -exports.{{nickname}} = function(args, res, next) { +exports.{{{operationId}}} = function(args, res, next) { /** - * parameters expected in the args: - {{#allParams}}* {{paramName}} ({{dataType}}) - {{/allParams}}**/ - {{^returnType}}// no response value expected for this operation + {{#summary}} + * {{{summary}}} + {{/summary}} + {{#notes}} + * {{{notes}}} + {{/notes}} + * + {{#allParams}} + * {{paramName}} {{{dataType}}} {{{description}}}{{^required}} (optional){{/required}} + {{/allParams}} + {{^returnType}} + * no response value expected for this operation {{/returnType}} + {{#returnType}} + * returns {{{returnType}}} + {{/returnType}} + **/ {{#returnType}} var examples = {}; - {{#examples}}examples['{{contentType}}'] = {{{example}}}; + {{#examples}} + examples['{{contentType}}'] = {{{example}}}; {{/examples}} - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } {{/returnType}} - {{^returnType}}res.end();{{/returnType}} + {{^returnType}} + res.end(); + {{/returnType}} } {{/operation}} diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js index 3748305bfbe..5ff24c0591f 100644 --- a/samples/server/petstore/nodejs/controllers/Pet.js +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -2,10 +2,8 @@ var url = require('url'); - var Pet = require('./PetService'); - module.exports.addPet = function addPet (req, res, next) { Pet.addPet(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index 55a4bf2b896..8a4235a35fc 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -2,29 +2,36 @@ exports.addPet = function(args, res, next) { /** - * parameters expected in the args: - * body (Pet) - **/ - // no response value expected for this operation + * Add a new pet to the store + * + * + * body Pet Pet object that needs to be added to the store + * no response value expected for this operation + **/ res.end(); } exports.deletePet = function(args, res, next) { /** - * parameters expected in the args: - * petId (Long) - * api_key (String) - **/ - // no response value expected for this operation + * Deletes a pet + * + * + * petId Long Pet id to delete + * api_key String (optional) + * no response value expected for this operation + **/ res.end(); } exports.findPetsByStatus = function(args, res, next) { /** - * parameters expected in the args: - * status (List) - **/ - var examples = {}; + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * + * status List Status values that need to be considered for filter + * returns List + **/ + var examples = {}; examples['application/json'] = [ { "tags" : [ { "id" : 123456789, @@ -39,22 +46,23 @@ exports.findPetsByStatus = function(args, res, next) { "name" : "doggie", "photoUrls" : [ "aeiou" ] } ]; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.findPetsByTags = function(args, res, next) { /** - * parameters expected in the args: - * tags (List) - **/ - var examples = {}; + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * tags List Tags to filter by + * returns List + **/ + var examples = {}; examples['application/json'] = [ { "tags" : [ { "id" : 123456789, @@ -69,22 +77,23 @@ exports.findPetsByTags = function(args, res, next) { "name" : "doggie", "photoUrls" : [ "aeiou" ] } ]; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.getPetById = function(args, res, next) { /** - * parameters expected in the args: - * petId (Long) - **/ - var examples = {}; + * Find pet by ID + * Returns a single pet + * + * petId Long ID of pet to return + * returns Pet + **/ + var examples = {}; examples['application/json'] = { "tags" : [ { "id" : 123456789, @@ -99,56 +108,59 @@ exports.getPetById = function(args, res, next) { "name" : "doggie", "photoUrls" : [ "aeiou" ] }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.updatePet = function(args, res, next) { /** - * parameters expected in the args: - * body (Pet) - **/ - // no response value expected for this operation + * Update an existing pet + * + * + * body Pet Pet object that needs to be added to the store + * no response value expected for this operation + **/ res.end(); } exports.updatePetWithForm = function(args, res, next) { /** - * parameters expected in the args: - * petId (Long) - * name (String) - * status (String) - **/ - // no response value expected for this operation + * Updates a pet in the store with form data + * + * + * petId Long ID of pet that needs to be updated + * name String Updated name of the pet (optional) + * status String Updated status of the pet (optional) + * no response value expected for this operation + **/ res.end(); } exports.uploadFile = function(args, res, next) { /** - * parameters expected in the args: - * petId (Long) - * additionalMetadata (String) - * file (file) - **/ - var examples = {}; + * uploads an image + * + * + * petId Long ID of pet to update + * additionalMetadata String Additional data to pass to server (optional) + * file File file to upload (optional) + * returns ApiResponse + **/ + var examples = {}; examples['application/json'] = { "message" : "aeiou", "code" : 123, "type" : "aeiou" }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } diff --git a/samples/server/petstore/nodejs/controllers/Store.js b/samples/server/petstore/nodejs/controllers/Store.js index ac67c740d29..94d86b7b590 100644 --- a/samples/server/petstore/nodejs/controllers/Store.js +++ b/samples/server/petstore/nodejs/controllers/Store.js @@ -2,10 +2,8 @@ var url = require('url'); - var Store = require('./StoreService'); - module.exports.deleteOrder = function deleteOrder (req, res, next) { Store.deleteOrder(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index 7095e70b66e..7da8e0ceb23 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -2,37 +2,43 @@ exports.deleteOrder = function(args, res, next) { /** - * parameters expected in the args: - * orderId (String) - **/ - // no response value expected for this operation + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * orderId String ID of the order that needs to be deleted + * no response value expected for this operation + **/ res.end(); } exports.getInventory = function(args, res, next) { /** - * parameters expected in the args: - **/ - var examples = {}; + * Returns pet inventories by status + * Returns a map of status codes to quantities + * + * returns Map + **/ + var examples = {}; examples['application/json'] = { "key" : 123 }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.getOrderById = function(args, res, next) { /** - * parameters expected in the args: - * orderId (Long) - **/ - var examples = {}; + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * orderId Long ID of pet that needs to be fetched + * returns Order + **/ + var examples = {}; examples['application/json'] = { "id" : 123456789, "petId" : 123456789, @@ -41,22 +47,23 @@ exports.getOrderById = function(args, res, next) { "quantity" : 123, "shipDate" : "2000-01-23T04:56:07.000+00:00" }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.placeOrder = function(args, res, next) { /** - * parameters expected in the args: - * body (Order) - **/ - var examples = {}; + * Place an order for a pet + * + * + * body Order order placed for purchasing the pet + * returns Order + **/ + var examples = {}; examples['application/json'] = { "id" : 123456789, "petId" : 123456789, @@ -65,13 +72,11 @@ exports.placeOrder = function(args, res, next) { "quantity" : 123, "shipDate" : "2000-01-23T04:56:07.000+00:00" }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } diff --git a/samples/server/petstore/nodejs/controllers/User.js b/samples/server/petstore/nodejs/controllers/User.js index bac1d7f6a88..4b118e8211d 100644 --- a/samples/server/petstore/nodejs/controllers/User.js +++ b/samples/server/petstore/nodejs/controllers/User.js @@ -2,10 +2,8 @@ var url = require('url'); - var User = require('./UserService'); - module.exports.createUser = function createUser (req, res, next) { User.createUser(req.swagger.params, res, next); }; diff --git a/samples/server/petstore/nodejs/controllers/UserService.js b/samples/server/petstore/nodejs/controllers/UserService.js index 69fc1a81391..99090323f78 100644 --- a/samples/server/petstore/nodejs/controllers/UserService.js +++ b/samples/server/petstore/nodejs/controllers/UserService.js @@ -2,46 +2,57 @@ exports.createUser = function(args, res, next) { /** - * parameters expected in the args: - * body (User) - **/ - // no response value expected for this operation + * Create user + * This can only be done by the logged in user. + * + * body User Created user object + * no response value expected for this operation + **/ res.end(); } exports.createUsersWithArrayInput = function(args, res, next) { /** - * parameters expected in the args: - * body (List) - **/ - // no response value expected for this operation + * Creates list of users with given input array + * + * + * body List List of user object + * no response value expected for this operation + **/ res.end(); } exports.createUsersWithListInput = function(args, res, next) { /** - * parameters expected in the args: - * body (List) - **/ - // no response value expected for this operation + * Creates list of users with given input array + * + * + * body List List of user object + * no response value expected for this operation + **/ res.end(); } exports.deleteUser = function(args, res, next) { /** - * parameters expected in the args: - * username (String) - **/ - // no response value expected for this operation + * Delete user + * This can only be done by the logged in user. + * + * username String The name that needs to be deleted + * no response value expected for this operation + **/ res.end(); } exports.getUserByName = function(args, res, next) { /** - * parameters expected in the args: - * username (String) - **/ - var examples = {}; + * Get user by user name + * + * + * username String The name that needs to be fetched. Use user1 for testing. + * returns User + **/ + var examples = {}; examples['application/json'] = { "id" : 123456789, "lastName" : "aeiou", @@ -52,49 +63,52 @@ exports.getUserByName = function(args, res, next) { "firstName" : "aeiou", "password" : "aeiou" }; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.loginUser = function(args, res, next) { /** - * parameters expected in the args: - * username (String) - * password (String) - **/ - var examples = {}; + * Logs user into the system + * + * + * username String The user name for login + * password String The password for login in clear text + * returns String + **/ + var examples = {}; examples['application/json'] = "aeiou"; - if(Object.keys(examples).length > 0) { + if (Object.keys(examples).length > 0) { res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify(examples[Object.keys(examples)[0]] || {}, null, 2)); - } - else { + } else { res.end(); } - } exports.logoutUser = function(args, res, next) { /** - * parameters expected in the args: - **/ - // no response value expected for this operation + * Logs out current logged in user session + * + * + * no response value expected for this operation + **/ res.end(); } exports.updateUser = function(args, res, next) { /** - * parameters expected in the args: - * username (String) - * body (User) - **/ - // no response value expected for this operation + * Updated user + * This can only be done by the logged in user. + * + * username String name that need to be deleted + * body User Updated user object + * no response value expected for this operation + **/ res.end(); } diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index d05c0ee2561..e5fccd69a52 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -6,7 +6,7 @@ "scripts": { "prestart": "npm install", "start": "node index.js" - }, + }, "keywords": [ "swagger" ], From fb3d4e61bb5c7f5ea343d8eac2d0842c2ffe685e Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 29 Dec 2016 23:45:59 +0800 Subject: [PATCH 204/269] roll back to latest working version of swagger paresr for codegen --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 2dd1fd7bad8..87d864fe692 100644 --- a/pom.xml +++ b/pom.xml @@ -850,7 +850,7 @@ - 1.0.25-SNAPSHOT + 1.0.24 2.11.1 2.3.4 1.5.10 From 0252d1a53483a2d808fc78ff1a73a8798be81250 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 3 Jan 2017 00:41:16 -0800 Subject: [PATCH 205/269] Update to latest swagger-core, parser versions (#4472) * updated to release versions * fixed defaultValue objects to strings * added top-level jackson version * added missing dependency, removed from swagger-core --- .../java/io/swagger/codegen/DefaultCodegen.java | 15 ++++++++++++--- modules/swagger-generator/pom.xml | 5 +++++ pom.xml | 5 +++-- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 6c3078a8ada..712b0e6d99f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2247,11 +2247,20 @@ public class DefaultCodegen { // move the defaultValue for headers, forms and params if (param instanceof QueryParameter) { - p.defaultValue = ((QueryParameter) param).getDefaultValue(); + QueryParameter qp = (QueryParameter) param; + if(qp.getDefaultValue() != null) { + p.defaultValue = qp.getDefaultValue().toString(); + } } else if (param instanceof HeaderParameter) { - p.defaultValue = ((HeaderParameter) param).getDefaultValue(); + HeaderParameter hp = (HeaderParameter) param; + if(hp.getDefaultValue() != null) { + p.defaultValue = hp.getDefaultValue().toString(); + } } else if (param instanceof FormParameter) { - p.defaultValue = ((FormParameter) param).getDefaultValue(); + FormParameter fp = (FormParameter) param; + if(fp.getDefaultValue() != null) { + p.defaultValue = fp.getDefaultValue().toString(); + } } p.vendorExtensions = param.getVendorExtensions(); diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index c086715639f..fcfcd0c9dca 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -218,6 +218,11 @@ org.testng testng
    + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + 2.5 diff --git a/pom.xml b/pom.xml index 87d864fe692..8a4792d1406 100644 --- a/pom.xml +++ b/pom.xml @@ -850,13 +850,14 @@ - 1.0.24 + 1.0.25 2.11.1 2.3.4 - 1.5.10 + 1.5.12 2.4 1.2 4.8.1 + 2.8.5 1.0.0 3.4 1.7.12 From c94e18abd84d4c69e8a53d434f07d651c4fb892a Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Tue, 3 Jan 2017 03:56:50 -0500 Subject: [PATCH 206/269] [codegen ignore] normalize path separator for Windows, add *.ext tests (#4476) * [codegen ignore] Fix windows paths for ignore processing * [codegen ignore] Add missing glob rule tests --- .../io/swagger/codegen/DefaultGenerator.java | 11 +++--- .../ignore/CodegenIgnoreProcessorTest.java | 2 + .../codegen/ignore/rules/FileRuleTest.java | 39 +++++++++++++++++++ 3 files changed, 47 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 228be1a3ef5..94d1579671e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -474,7 +474,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (!of.isDirectory()) { of.mkdirs(); } - String outputFilename = outputFolder + File.separator + support.destinationFilename; + String outputFilename = outputFolder + File.separator + support.destinationFilename.replace('/', File.separatorChar); if (!config.shouldOverwrite(outputFilename)) { LOGGER.info("Skipped overwriting " + outputFilename); continue; @@ -657,7 +657,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } private File processTemplateToFile(Map templateData, String templateName, String outputFilename) throws IOException { - if(ignoreProcessor.allowsFile(new File(outputFilename.replaceAll("//", "/")))) { + String adjustedOutputFilename = outputFilename.replaceAll("//", "/").replace('/', File.separatorChar); + if(ignoreProcessor.allowsFile(new File(adjustedOutputFilename))) { String templateFile = getFullTemplateFile(config, templateName); String template = readTemplate(templateFile); Mustache.Compiler compiler = Mustache.compiler(); @@ -672,11 +673,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { .defaultValue("") .compile(template); - writeToFile(outputFilename, tmpl.execute(templateData)); - return new File(outputFilename); + writeToFile(adjustedOutputFilename, tmpl.execute(templateData)); + return new File(adjustedOutputFilename); } - LOGGER.info("Skipped generation of " + outputFilename + " due to rule in .swagger-codegen-ignore"); + LOGGER.info("Skipped generation of " + adjustedOutputFilename + " due to rule in .swagger-codegen-ignore"); return null; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java index ef30ca48331..da4a46f4af8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/CodegenIgnoreProcessorTest.java @@ -107,6 +107,8 @@ public class CodegenIgnoreProcessorTest { return new Object[] { // Matching filenames new CodegenIgnoreProcessorTest("build.sh", "build.sh", "A file when matching should ignore.").ignored(), + new CodegenIgnoreProcessorTest("build.sh", "*.sh", "A file when matching glob should ignore.").ignored(), + new CodegenIgnoreProcessorTest("src/build.sh", "*.sh", "A nested file when matching non-nested simple glob should allow.").allowed(), new CodegenIgnoreProcessorTest("src/build.sh", "**/build.sh", "A file when matching nested files should ignore.").ignored(), new CodegenIgnoreProcessorTest("Build.sh", "build.sh", "A file when non-matching should allow.").allowed().skipOnCondition(SystemUtils.IS_OS_WINDOWS), new CodegenIgnoreProcessorTest("build.sh", "/build.sh", "A rooted file when matching should ignore.").ignored(), diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java index f093507d84c..401bb7031a7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ignore/rules/FileRuleTest.java @@ -67,4 +67,43 @@ public class FileRuleTest { assertFalse(actual); } + @Test + public void testGlobbingRecursive() throws Exception { + // Arrange + final String definition = "*.txt"; + final String relativePath = "path/to/some/nested/location/xyzzy.txt"; + + // Act + final List syntax = Arrays.asList( + new Part(IgnoreLineParser.Token.MATCH_ALL), + new Part(IgnoreLineParser.Token.DIRECTORY_MARKER), + new Part(IgnoreLineParser.Token.MATCH_ANY), + new Part(IgnoreLineParser.Token.TEXT, ".txt") + ); + + Rule rule = new FileRule(syntax, definition); + Boolean actual = rule.matches(relativePath); + + // Assert + assertTrue(actual); + } + + @Test + public void testGlobbingNotRecursive() throws Exception { + // Arrange + final String definition = "*.txt"; + final String relativePath = "path/to/some/nested/location/xyzzy.txt"; + + // Act + final List syntax = Arrays.asList( + new Part(IgnoreLineParser.Token.MATCH_ANY), + new Part(IgnoreLineParser.Token.TEXT, ".txt") + ); + + Rule rule = new FileRule(syntax, definition); + Boolean actual = rule.matches(relativePath); + + // Assert + assertFalse(actual); + } } \ No newline at end of file From cb9a1b3b53d1d5a1d1416ce3589ec040870c063e Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Tue, 3 Jan 2017 05:31:26 -0500 Subject: [PATCH 207/269] [csharp] Use default rather than null in ctor (#4145) --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 4 ++-- .../src/main/resources/csharp/modelGeneric.mustache | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 712b0e6d99f..c1daf3ce8ab 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2242,7 +2242,7 @@ public class DefaultCodegen { p.jsonSchema = Json.pretty(param); if (System.getProperty("debugParser") != null) { - LOGGER.info("working on Parameter " + param); + LOGGER.info("working on Parameter " + param.getName()); } // move the defaultValue for headers, forms and params @@ -2271,7 +2271,7 @@ public class DefaultCodegen { String collectionFormat = null; String type = qp.getType(); if (null == type) { - LOGGER.warn("Type is NULL for Serializable Parameter: " + param); + LOGGER.warn("Type is NULL for Serializable Parameter: " + param.getName()); } if ("array".equals(type)) { // for array parameter Property inner = qp.getItems(); diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 8f0ec47a1fa..5e1d0721dc2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -47,7 +47,7 @@ {{#hasOnlyReadOnly}} [JsonConstructorAttribute] {{/hasOnlyReadOnly}} - public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = null{{^-last}}, {{/-last}}{{/readWriteVars}}) + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}) { {{#vars}} {{^isReadOnly}} From 3f66e27a92c83e474a428684623ed81847c321e9 Mon Sep 17 00:00:00 2001 From: Ashish Jain Date: Wed, 4 Jan 2017 09:47:14 -0500 Subject: [PATCH 208/269] Only updated README.md file (#4485) Added reference to snapcx website, as we provide swagger 2.0 specs public APIs. --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 851230f7ec5..c45589232b4 100644 --- a/README.md +++ b/README.md @@ -820,6 +820,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Shine Solutions](https://shinesolutions.com/) - [Skurt](http://www.skurt.com) - [SmartRecruiters](https://www.smartrecruiters.com/) +- [snapCX](https://snapcx.io) - [SRC](https://www.src.si/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) From 1a1d0aebc8dacc399b352e9ba420d9e33de6c47c Mon Sep 17 00:00:00 2001 From: Johannes Fiala Date: Tue, 3 Jan 2017 05:31:26 -0500 Subject: [PATCH 209/269] add beanvalidation to jersey1 and jersey2 #4091 --- .../io/swagger/codegen/DefaultCodegen.java | 4 +- .../languages/AbstractJavaCodegen.java | 13 ++++++ .../languages/JavaJerseyServerCodegen.java | 19 ++++++++- .../src/main/resources/JavaJaxRS/api.mustache | 3 ++ .../JavaJaxRS/beanValidation.mustache | 42 +++++++++++++++++++ .../beanValidationPathParams.mustache | 1 + .../beanValidationQueryParams.mustache | 1 + .../JavaJaxRS/libraries/jersey1/api.mustache | 3 ++ .../JavaJaxRS/libraries/jersey1/pom.mustache | 9 ++++ .../main/resources/JavaJaxRS/model.mustache | 3 ++ .../main/resources/JavaJaxRS/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/pom.mustache | 10 +++++ .../JavaJaxRS/servicePathParams.mustache | 2 +- .../JavaJaxRS/serviceQueryParams.mustache | 2 +- .../resources/csharp/modelGeneric.mustache | 2 +- .../src/gen/java/io/swagger/api/PetApi.java | 40 ++++++++++-------- .../java/io/swagger/api/PetApiService.java | 7 ++-- .../src/gen/java/io/swagger/api/StoreApi.java | 13 +++--- .../java/io/swagger/api/StoreApiService.java | 2 +- .../src/gen/java/io/swagger/api/UserApi.java | 29 ++++++------- .../java/io/swagger/api/UserApiService.java | 2 +- .../gen/java/io/swagger/model/Category.java | 5 ++- .../src/gen/java/io/swagger/model/Order.java | 7 ++-- .../src/gen/java/io/swagger/model/Pet.java | 7 +++- .../src/gen/java/io/swagger/model/Tag.java | 5 ++- .../src/gen/java/io/swagger/model/User.java | 5 ++- .../swagger/api/impl/PetApiServiceImpl.java | 7 ++-- .../swagger/api/impl/StoreApiServiceImpl.java | 2 +- .../swagger/api/impl/UserApiServiceImpl.java | 2 +- .../src/gen/java/io/swagger/api/PetApi.java | 40 ++++++++++-------- .../java/io/swagger/api/PetApiService.java | 7 ++-- .../src/gen/java/io/swagger/api/StoreApi.java | 13 +++--- .../java/io/swagger/api/StoreApiService.java | 2 +- .../src/gen/java/io/swagger/api/UserApi.java | 29 ++++++------- .../java/io/swagger/api/UserApiService.java | 2 +- .../gen/java/io/swagger/model/Category.java | 5 ++- .../src/gen/java/io/swagger/model/Order.java | 7 ++-- .../src/gen/java/io/swagger/model/Pet.java | 7 +++- .../src/gen/java/io/swagger/model/Tag.java | 5 ++- .../src/gen/java/io/swagger/model/User.java | 5 ++- .../swagger/api/impl/PetApiServiceImpl.java | 7 ++-- .../swagger/api/impl/StoreApiServiceImpl.java | 2 +- .../swagger/api/impl/UserApiServiceImpl.java | 2 +- 43 files changed, 252 insertions(+), 130 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 712b0e6d99f..c1daf3ce8ab 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2242,7 +2242,7 @@ public class DefaultCodegen { p.jsonSchema = Json.pretty(param); if (System.getProperty("debugParser") != null) { - LOGGER.info("working on Parameter " + param); + LOGGER.info("working on Parameter " + param.getName()); } // move the defaultValue for headers, forms and params @@ -2271,7 +2271,7 @@ public class DefaultCodegen { String collectionFormat = null; String type = qp.getType(); if (null == type) { - LOGGER.warn("Type is NULL for Serializable Parameter: " + param); + LOGGER.warn("Type is NULL for Serializable Parameter: " + param.getName()); } if ("array".equals(type)) { // for array parameter Property inner = qp.getItems(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 2f5860584e0..faa08458dfd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -1000,5 +1000,18 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public String toRegularExpression(String pattern) { return escapeText(pattern); } + + public boolean convertPropertyToBoolean(String propertyKey) { + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + } + + return booleanValue; + } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index b8aef14410b..f60ac8ad7b3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import java.util.*; @@ -8,11 +9,12 @@ import java.util.*; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; -public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { +public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen implements BeanValidationFeatures { protected static final String LIBRARY_JERSEY1 = "jersey1"; protected static final String LIBRARY_JERSEY2 = "jersey2"; - + protected boolean useBeanValidation = true; + /** * Default library template to use. (Default:{@value #DEFAULT_LIBRARY}) */ @@ -45,6 +47,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { cliOptions.add(library); cliOptions.add(CliOption.newBoolean(SUPPORT_JAVA6, "Whether to support Java6 with the Jersey1/2 library.")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); } @Override @@ -84,6 +87,14 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { if (StringUtils.isEmpty(library)) { setLibrary(DEFAULT_LIBRARY); } + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); @@ -160,5 +171,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { opList.add(co); co.baseName = basePath; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 59b71d2ba47..d70958346f2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -22,6 +22,9 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} @Path("/{{baseName}}") {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache new file mode 100644 index 00000000000..f13ed596859 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache @@ -0,0 +1,42 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) + {{/maxItems}} + {{/minItems}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache index 59074d1af13..e77215600f0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache @@ -8,6 +8,9 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache index d21444dda26..26b934f2722 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache @@ -158,6 +158,15 @@ +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index b84bfee6a85..1d4785dda12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -13,6 +13,9 @@ import org.apache.commons.lang3.ObjectUtils; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index f3a36ecc387..4aa400d700e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -67,7 +67,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } {{^isReadOnly}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 19cbd0a95ad..d5ff9b0055a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -153,6 +153,16 @@ ${commons_io_version} {{/supportJava6}} + +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache index 6829cf8c7a6..07b519cba5e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache index ff79730471d..e3fd6c6ce76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 8f0ec47a1fa..5e1d0721dc2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -47,7 +47,7 @@ {{#hasOnlyReadOnly}} [JsonConstructorAttribute] {{/hasOnlyReadOnly}} - public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = null{{^-last}}, {{/-last}}{{/readWriteVars}}) + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}) { {{#vars}} {{^isReadOnly}} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 076f6051db0..263d332e048 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -8,9 +8,9 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -37,7 +37,7 @@ public class PetApi { @POST @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -47,7 +47,7 @@ public class PetApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) public Response addPet( - @ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body, + @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.addPet(body,securityContext); @@ -55,7 +55,7 @@ public class PetApi { @DELETE @Path("/{petId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -74,7 +74,7 @@ public class PetApi { @GET @Path("/findByStatus") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -85,7 +85,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) public Response findPetsByStatus( - @ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status, + @ApiParam(value = "Status values that need to be considered for filter", allowableValues="available, pending, sold", defaultValue="available") @DefaultValue("available") @QueryParam("status") List status, @Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); @@ -93,7 +93,7 @@ public class PetApi { @GET @Path("/findByTags") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -104,7 +104,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) public Response findPetsByTags( - @ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags, + @ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags, @Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); @@ -112,8 +112,12 @@ public class PetApi { @GET @Path("/{petId}") - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Produces({ "application/json", "application/xml" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }), @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @@ -121,7 +125,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) public Response getPetById( - @ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId, @Context SecurityContext securityContext) throws NotFoundException { return delegate.getPetById(petId,securityContext); @@ -129,7 +133,7 @@ public class PetApi { @PUT @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -141,7 +145,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) public Response updatePet( - @ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body, + @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePet(body,securityContext); @@ -149,7 +153,7 @@ public class PetApi { @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -159,7 +163,7 @@ public class PetApi { @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) public Response updatePetWithForm( - @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String petId, @ApiParam(value = "Updated name of the pet") @FormParam("name") String name, @ApiParam(value = "Updated status of the pet") @FormParam("status") String status, @Context SecurityContext securityContext) @@ -169,15 +173,15 @@ public class PetApi { @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Produces({ "application/json", "application/xml" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet" }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) public Response uploadFile( @ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, @FormDataParam("additionalMetadata") String additionalMetadata, diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index df33e262880..255d31f3e4f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -6,7 +6,6 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -26,15 +25,15 @@ public abstract class PetApiService { throws NotFoundException; public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus(List status,SecurityContext securityContext) + public abstract Response findPetsByStatus( List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags(List tags,SecurityContext securityContext) + public abstract Response findPetsByTags( List tags,SecurityContext securityContext) throws NotFoundException; public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) + public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException; public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java index 6742c34fe3e..f6cbbe50ec4 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.util.Map; import io.swagger.model.Order; @@ -36,7 +37,7 @@ public class StoreApi { @DELETE @Path("/order/{orderId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), @@ -50,7 +51,7 @@ public class StoreApi { @GET @Path("/inventory") - @Produces({ "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "store", }) @@ -64,14 +65,14 @@ public class StoreApi { @GET @Path("/order/{orderId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) public Response getOrderById( - @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId, + @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId, @Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); @@ -79,13 +80,13 @@ public class StoreApi { @POST @Path("/order") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) public Response placeOrder( - @ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body, + @ApiParam(value = "order placed for purchasing the pet" ) Order body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.placeOrder(body,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java index c065b6c780c..9b5dde7d40e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java @@ -25,7 +25,7 @@ public abstract class StoreApiService { throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(Long orderId,SecurityContext securityContext) + public abstract Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java index ffa97ab4649..5ecfdd9b9ea 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.util.List; import io.swagger.model.User; @@ -36,12 +37,12 @@ public class UserApi { @POST - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) public Response createUser( - @ApiParam(value = "Created user object" ,required=true) User body, + @ApiParam(value = "Created user object" ) User body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); @@ -49,12 +50,12 @@ public class UserApi { @POST @Path("/createWithArray") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) public Response createUsersWithArrayInput( - @ApiParam(value = "List of user object" ,required=true) List body, + @ApiParam(value = "List of user object" ) List body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); @@ -62,12 +63,12 @@ public class UserApi { @POST @Path("/createWithList") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) public Response createUsersWithListInput( - @ApiParam(value = "List of user object" ,required=true) List body, + @ApiParam(value = "List of user object" ) List body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); @@ -75,7 +76,7 @@ public class UserApi { @DELETE @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), @@ -89,7 +90,7 @@ public class UserApi { @GET @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), @@ -104,14 +105,14 @@ public class UserApi { @GET @Path("/login") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) public Response loginUser( - @ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username, - @ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password, + @ApiParam(value = "The user name for login") @QueryParam("username") String username, + @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password, @Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); @@ -119,7 +120,7 @@ public class UserApi { @GET @Path("/logout") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -131,14 +132,14 @@ public class UserApi { @PUT @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) public Response updateUser( @ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, - @ApiParam(value = "Updated user object" ,required=true) User body, + @ApiParam(value = "Updated user object" ) User body, @Context SecurityContext securityContext) throws NotFoundException { return delegate.updateUser(username,body,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java index a3bcd0da8fd..97482052000 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java @@ -31,7 +31,7 @@ public abstract class UserApiService { throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser(String username,String password,SecurityContext securityContext) + public abstract Response loginUser( String username, String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java index 62a809814b5..9d5452ac70c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at
    http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Category diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java index 11e8c7fd70c..c37f8f4334c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -20,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; +import javax.validation.constraints.*; /** * Order @@ -75,7 +76,7 @@ public class Order { private StatusEnum status = null; @JsonProperty("complete") - private Boolean complete = false; + private Boolean complete = null; public Order id(Long id) { this.id = id; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index e7e94cc89a8..a12394dabce 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -23,6 +23,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * Pet @@ -126,6 +127,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -149,6 +151,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java index 4d1d23d8b92..27bce18c966 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Tag diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java index 779377d4578..700b1165976 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * User diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index d775f8dc4a0..2802343d2a1 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -6,7 +6,6 @@ import io.swagger.model.*; import com.sun.jersey.multipart.FormDataParam; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -35,13 +34,13 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByStatus(List status, SecurityContext securityContext) + public Response findPetsByStatus( List status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByTags(List tags, SecurityContext securityContext) + public Response findPetsByTags( List tags, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); @@ -59,7 +58,7 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) + public Response updatePetWithForm(String petId, String name, String status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 2b00aa8fad0..e6f65e0958f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -34,7 +34,7 @@ public class StoreApiServiceImpl extends StoreApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getOrderById(Long orderId, SecurityContext securityContext) + public Response getOrderById(String orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index f8cf78613d9..35a4ec4092b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -52,7 +52,7 @@ public class UserApiServiceImpl extends UserApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response loginUser(String username, String password, SecurityContext securityContext) + public Response loginUser( String username, String password, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java index 7f6905ce223..430606b5f2e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -8,7 +8,6 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -23,6 +22,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/pet") @@ -35,7 +35,7 @@ public class PetApi { @POST @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -44,7 +44,7 @@ public class PetApi { }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.addPet(body,securityContext); @@ -52,7 +52,7 @@ public class PetApi { @DELETE @Path("/{petId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -70,7 +70,7 @@ public class PetApi { @GET @Path("/findByStatus") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -81,7 +81,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", allowableValues="available, pending, sold", defaultValue="available") @DefaultValue("available") @QueryParam("status") List status ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); @@ -89,7 +89,7 @@ public class PetApi { @GET @Path("/findByTags") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -100,7 +100,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags + public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); @@ -108,8 +108,12 @@ public class PetApi { @GET @Path("/{petId}") - @Produces({ "application/xml", "application/json" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Produces({ "application/json", "application/xml" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }), @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @@ -118,7 +122,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId + public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getPetById(petId,securityContext); @@ -126,7 +130,7 @@ public class PetApi { @PUT @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -139,7 +143,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePet(body,securityContext); @@ -147,7 +151,7 @@ public class PetApi { @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @@ -156,7 +160,7 @@ public class PetApi { }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String petId ,@ApiParam(value = "Updated name of the pet") @FormParam("name") String name ,@ApiParam(value = "Updated status of the pet") @FormParam("status") String status ,@Context SecurityContext securityContext) @@ -166,15 +170,15 @@ public class PetApi { @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Produces({ "application/json", "application/xml" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = void.class, authorizations = { @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId ,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata , diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index 76026a64c8b..b692895d979 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -6,7 +6,6 @@ import io.swagger.model.*; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -21,10 +20,10 @@ import javax.ws.rs.core.SecurityContext; public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByStatus( List status,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByTags( List tags,SecurityContext securityContext) throws NotFoundException; public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException; public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java index 6c4c40b97cc..56a5cf6ce36 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/store") @@ -34,7 +35,7 @@ public class StoreApi { @DELETE @Path("/order/{orderId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), @@ -48,7 +49,7 @@ public class StoreApi { @GET @Path("/inventory") - @Produces({ "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "store", }) @@ -61,7 +62,7 @@ public class StoreApi { @GET @Path("/order/{orderId}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @@ -69,7 +70,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); @@ -77,13 +78,13 @@ public class StoreApi { @POST @Path("/order") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.placeOrder(body,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java index 5ef766d6aa7..15cea4db0d3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -20,6 +20,6 @@ import javax.ws.rs.core.SecurityContext; public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(Long orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java index 50b17bcd568..5ccee5dca7a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/user") @@ -34,11 +35,11 @@ public class UserApi { @POST - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body + public Response createUser(@ApiParam(value = "Created user object" ) User body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); @@ -46,11 +47,11 @@ public class UserApi { @POST @Path("/createWithArray") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); @@ -58,11 +59,11 @@ public class UserApi { @POST @Path("/createWithList") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); @@ -70,7 +71,7 @@ public class UserApi { @DELETE @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), @@ -84,7 +85,7 @@ public class UserApi { @GET @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), @@ -100,14 +101,14 @@ public class UserApi { @GET @Path("/login") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username -,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password + public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username +,@ApiParam(value = "The password for login in clear text") @QueryParam("password") String password ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); @@ -115,7 +116,7 @@ public class UserApi { @GET @Path("/logout") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -126,14 +127,14 @@ public class UserApi { @PUT @Path("/{username}") - @Produces({ "application/xml", "application/json" }) + @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username -,@ApiParam(value = "Updated user object" ,required=true) User body +,@ApiParam(value = "Updated user object" ) User body ,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updateUser(username,body,securityContext); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java index e0e65657bed..45375dff120 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -23,7 +23,7 @@ public abstract class UserApiService { public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; + public abstract Response loginUser( String username, String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index 62a809814b5..9d5452ac70c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Category diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index 11e8c7fd70c..c37f8f4334c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -20,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; +import javax.validation.constraints.*; /** * Order @@ -75,7 +76,7 @@ public class Order { private StatusEnum status = null; @JsonProperty("complete") - private Boolean complete = false; + private Boolean complete = null; public Order id(Long id) { this.id = id; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index e7e94cc89a8..a12394dabce 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -23,6 +23,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * Pet @@ -126,6 +127,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -149,6 +151,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index 4d1d23d8b92..27bce18c966 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Tag diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 779377d4578..700b1165976 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -1,9 +1,9 @@ /* * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters * * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io + * Contact: apiteam@wordnik.com * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * User diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 856243a387e..8798db5272d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -4,7 +4,6 @@ import io.swagger.api.*; import io.swagger.model.*; import java.io.File; -import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; import java.util.List; @@ -30,12 +29,12 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByStatus(List status, SecurityContext securityContext) throws NotFoundException { + public Response findPetsByStatus( List status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByTags(List tags, SecurityContext securityContext) throws NotFoundException { + public Response findPetsByTags( List tags, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @@ -50,7 +49,7 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { + public Response updatePetWithForm(String petId, String name, String status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 85e14b0bbe5..30bb60a33b1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -29,7 +29,7 @@ public class StoreApiServiceImpl extends StoreApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getOrderById(Long orderId, SecurityContext securityContext) throws NotFoundException { + public Response getOrderById(String orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 0d59ad51c5a..fb84c95879a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -44,7 +44,7 @@ public class UserApiServiceImpl extends UserApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response loginUser(String username, String password, SecurityContext securityContext) throws NotFoundException { + public Response loginUser( String username, String password, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } From 42a04916964f004477fc0476003ce78db9879cdd Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 5 Jan 2017 16:30:04 +0800 Subject: [PATCH 210/269] add https://www.fastly.com/ --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index c45589232b4..3024c333569 100644 --- a/README.md +++ b/README.md @@ -775,6 +775,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [eureka](http://eure.jp/) - [everystory.us](http://everystory.us) - [Expected Behavior](http://www.expectedbehavior.com/) +- [Fastly](https://www.fastly.com/) - [Flat](https://flat.io) - [Finder](http://en.finder.pl/) - [FH Münster - University of Applied Sciences](http://www.fh-muenster.de) From 6a080d3a0c26015262120cdd9e7f4f2feeb59b23 Mon Sep 17 00:00:00 2001 From: Takuro Wada Date: Fri, 6 Jan 2017 01:55:55 +0900 Subject: [PATCH 211/269] add safe argument to quote method in python template to avoid unquoted parameter in path parameter (#4457) Closes #4391 --- .../src/main/resources/python/api_client.mustache | 2 +- samples/client/petstore/python/petstore_api/api_client.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index eb8b73c7bdf..9fa64efcca5 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -107,7 +107,7 @@ class ApiClient(object): collection_formats) for k, v in path_params: resource_path = resource_path.replace( - '{%s}' % k, quote(str(v))) + '{%s}' % k, quote(str(v), safe="")) # query parameters if query_params: diff --git a/samples/client/petstore/python/petstore_api/api_client.py b/samples/client/petstore/python/petstore_api/api_client.py index d4a40cfcbfd..f161cfb9f99 100644 --- a/samples/client/petstore/python/petstore_api/api_client.py +++ b/samples/client/petstore/python/petstore_api/api_client.py @@ -116,7 +116,7 @@ class ApiClient(object): collection_formats) for k, v in path_params: resource_path = resource_path.replace( - '{%s}' % k, quote(str(v))) + '{%s}' % k, quote(str(v), safe="")) # query parameters if query_params: From b224474a4306a8ab603293fc3bff666c77f5512c Mon Sep 17 00:00:00 2001 From: Brian Shamblen Date: Thu, 5 Jan 2017 09:03:18 -0800 Subject: [PATCH 212/269] Fixes #4481 (#4493) --- .../src/main/resources/htmlDocs2/index.mustache | 2 +- samples/html2/index.html | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index 3f5cb05b3dc..a6b8ad90c7a 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -222,7 +222,7 @@
    -
    curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    +
    curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]"{{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}}{{#hasProduces}} -H "Accept: {{#produces}}{{{mediaType}}}{{#hasMore}},{{/hasMore}}{{/produces}}"{{/hasProduces}}{{#hasConsumes}} -H "Content-Type: {{#consumes}}{{{mediaType}}}{{#hasMore}},{{/hasMore}}{{/consumes}}"{{/hasConsumes}} -H "Authorization: Basic [[basicHash]]"{{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    {{>sample_java}}
    diff --git a/samples/html2/index.html b/samples/html2/index.html index 26881d448da..42de47c06d2 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -2128,7 +2128,7 @@ try {
    -
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    +
    curl -X get -H "api_key: [[apiKey]]" "http://petstore.swagger.io/v2/pet/{petId}"
    import io.swagger.client.*;
    @@ -3140,7 +3140,7 @@ namespace Example
                 var apiInstance = new PetApi();
                 var petId = 789;  // Long | ID of pet to update
                 var additionalMetadata = additionalMetadata_example;  // String | Additional data to pass to server (optional) 
    -            var file = /path/to/file.txt;  // File | file to upload (optional) 
    +            var file = new File(); // File | file to upload (optional) 
     
                 try
                 {
    @@ -3531,7 +3531,7 @@ try {
       "description" : "ID of the order that needs to be deleted",
       "required" : true,
       "type" : "string",
    -  "minimum" : 1.0
    +  "minimum" : 1
     };
     													var schema = schemaWrapper;
     
    @@ -3597,7 +3597,7 @@ try {
     
                             
    -
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    +
    curl -X get -H "api_key: [[apiKey]]" "http://petstore.swagger.io/v2/store/inventory"
    import io.swagger.client.*;
    @@ -4005,8 +4005,8 @@ try {
       "description" : "ID of pet that needs to be fetched",
       "required" : true,
       "type" : "integer",
    -  "maximum" : 5.0,
    -  "minimum" : 1.0,
    +  "maximum" : 5,
    +  "minimum" : 1,
       "format" : "int64"
     };
     													var schema = schemaWrapper;
    @@ -6303,7 +6303,7 @@ try {
               
    - Generated 2016-12-16T18:07:47.864+08:00 + Generated 2017-01-03T10:36:42.650-08:00
    From aa1dc0fdd2589835931bdd472f890778159de310 Mon Sep 17 00:00:00 2001 From: Simon Morris Date: Thu, 5 Jan 2017 09:09:32 -0800 Subject: [PATCH 213/269] Updated Nancy from 1.4.1 to 1.4.3 (#4482) --- .../src/main/resources/nancyfx/Project.mustache | 4 ++-- .../main/resources/nancyfx/packages.config.mustache | 2 +- samples/server/petstore/nancyfx/IO.Swagger.sln | 10 +++++----- .../petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj | 6 +++--- .../petstore/nancyfx/src/IO.Swagger/packages.config | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache index c4a06b60070..8ff5398633d 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache @@ -39,8 +39,8 @@ bin\Release\{{packageName}}.XML - - ..\..\packages\Nancy.1.4.1\lib\net40\Nancy.dll + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll True diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache index 58198276a42..c511c50acc8 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache @@ -1,6 +1,6 @@ - + diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 09301395de7..38fb0ef476a 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{3B55ED13-A471-44B1-A8D5-C158723C0A0C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{9A5C2190-C960-4808-93CB-8721C1022F9B}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.Build.0 = Debug|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.ActiveCfg = Release|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.Build.0 = Release|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Debug|Any CPU.Build.0 = Debug|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Release|Any CPU.ActiveCfg = Release|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index a103786b912..8bccfa94485 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {3B55ED13-A471-44B1-A8D5-C158723C0A0C} + {9A5C2190-C960-4808-93CB-8721C1022F9B} Library Properties IO.Swagger.v2 @@ -31,8 +31,8 @@ bin\Release\IO.Swagger.XML - - ..\..\packages\Nancy.1.4.1\lib\net40\Nancy.dll + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll True diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config index 2575d1b4d77..e3401566e5d 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config @@ -1,6 +1,6 @@ - + From 43ab14b200607682e5ab836fcd91b48df003c4f8 Mon Sep 17 00:00:00 2001 From: Brian Voss Date: Fri, 6 Jan 2017 03:14:39 -0800 Subject: [PATCH 214/269] Adding Curl connect timeout configuration to PHP generation templates (#4500) --- .../src/main/resources/php/ApiClient.mustache | 5 +++ .../main/resources/php/configuration.mustache | 34 +++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 27d02e1d33d..6faa386a01a 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -153,6 +153,11 @@ class ApiClient if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 4877db1db29..0d82dc21923 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -87,6 +87,13 @@ class Configuration */ protected $curlTimeout = 0; + /** + * Timeout (second) of the HTTP connection, by default set to 0, no timeout + * + * @var string + */ + protected $curlConnectTimeout = 0; + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * @@ -370,6 +377,33 @@ class Configuration return $this->curlTimeout; } + /** + * Sets the HTTP connect timeout value + * + * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] + * + * @return Configuration + */ + public function setCurlConnectTimeout($seconds) + { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + } + + $this->curlConnectTimeout = $seconds; + return $this; + } + + /** + * Gets the HTTP connect timeout value + * + * @return string HTTP connect timeout value + */ + public function getCurlConnectTimeout() + { + return $this->curlConnectTimeout; + } + /** * Sets debug flag * From df0c54d0432b8a97a1157fe39eb41236aa357b0d Mon Sep 17 00:00:00 2001 From: Kevin Locke Date: Fri, 6 Jan 2017 04:30:47 -0700 Subject: [PATCH 215/269] Support the empty string as an enumeration value (#4450) When a string enumeration has the empty string as one of its available values, the generated code for many languages is invalid because the empty string can not be used as an identifier. As with numbers and symbols, provide a mapping to an English name which can be used as a replacement. In this case, "empty" for the empty string/empty value. Signed-off-by: Kevin Locke --- .../main/java/io/swagger/codegen/DefaultCodegen.java | 4 ++++ .../codegen/languages/AbstractCSharpCodegen.java | 4 ++++ .../swagger/codegen/languages/AbstractJavaCodegen.java | 4 ++++ .../swagger/codegen/languages/AbstractPhpCodegen.java | 4 ++++ .../languages/AbstractTypeScriptClientCodegen.java | 4 ++++ .../swagger/codegen/languages/CSharpClientCodegen.java | 4 ++++ .../codegen/languages/JavascriptClientCodegen.java | 4 ++++ .../codegen/languages/NancyFXServerCodegen.java | 4 ++++ .../io/swagger/codegen/languages/PhpClientCodegen.java | 4 ++++ .../swagger/codegen/languages/RubyClientCodegen.java | 4 ++++ .../io/swagger/codegen/languages/Swift3Codegen.java | 4 ++++ .../io/swagger/codegen/languages/SwiftCodegen.java | 4 ++++ ...etstore-with-fake-endpoints-models-for-testing.yaml | 1 + .../SwaggerClient/src/IO.Swagger/Model/EnumTest.cs | 8 +++++++- .../src/IO.Swagger/Model/EnumTest.cs | 8 +++++++- .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- samples/client/petstore/java/jersey1/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- .../petstore/java/jersey2-java6/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- .../petstore/java/jersey2-java8/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- samples/client/petstore/java/jersey2/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- .../java/okhttp-gson-parcelableModel/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 5 ++++- .../client/petstore/java/okhttp-gson/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 5 ++++- .../main/java/io/swagger/client/model/EnumTest.java | 5 ++++- .../petstore/java/retrofit2-play24/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 4 +++- .../client/petstore/java/retrofit2/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 5 ++++- .../client/petstore/java/retrofit2rx/docs/EnumTest.md | 1 + .../main/java/io/swagger/client/model/EnumTest.java | 5 ++++- .../petstore/javascript-promise/docs/EnumTest.md | 2 ++ .../petstore/javascript-promise/src/model/EnumTest.js | 7 ++++++- samples/client/petstore/javascript/docs/EnumTest.md | 2 ++ .../client/petstore/javascript/src/model/EnumTest.js | 7 ++++++- .../php/SwaggerClient-php/lib/Model/EnumTest.php | 10 ++++++---- .../petstore/python/petstore_api/models/enum_test.py | 2 +- .../petstore/ruby/lib/petstore/models/enum_test.rb | 4 ++-- .../Classes/Swaggers/Models/EnumTest.swift | 1 + .../Classes/Swaggers/Models/EnumTest.swift | 1 + .../Classes/Swaggers/Models/EnumTest.swift | 1 + .../src/gen/java/io/swagger/model/EnumTest.java | 4 +++- .../java-inflector/src/main/swagger/swagger.yaml | 1 + .../src/gen/java/io/swagger/model/EnumTest.java | 4 +++- .../src/gen/java/io/swagger/model/EnumTest.java | 4 +++- .../src/gen/java/io/swagger/model/EnumTest.java | 4 +++- .../src/main/java/io/swagger/model/EnumTest.java | 4 +++- .../src/main/java/io/swagger/model/EnumTest.java | 4 +++- .../src/main/java/io/swagger/model/EnumTest.java | 4 +++- 53 files changed, 160 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index c1daf3ce8ab..a6d2d2ffe06 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -303,6 +303,10 @@ public class DefaultCodegen { * @return the sanitized variable name for enum */ public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "EMPTY"; + } + String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 922e9213add..16945708fa2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -615,6 +615,10 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 2f5860584e0..01193f8a0aa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -808,6 +808,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "EMPTY"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return getSymbolName(value).toUpperCase(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java index f0eb365d0c8..c568f6b302f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -589,6 +589,10 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return (getSymbolName(name)).toUpperCase(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 2fccf1061cf..96505626911 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -286,6 +286,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 26df3d83e5c..c70749392cf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -494,6 +494,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return camelize(getSymbolName(value)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 8a1ff5ce1d2..9d661b88d3c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -1021,6 +1021,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "empty"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return (getSymbolName(value)).toUpperCase(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 3e2c3432356..44f31b25eb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -292,6 +292,10 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { @Override public String toEnumVarName(final String name, final String datatype) { + if (name.length() == 0) { + return "Empty"; + } + final String enumName = camelize( sanitizeName(name) .replaceFirst("^_", "") diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 4748513686b..f054038d134 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -644,6 +644,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = name; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 390a06335c8..a8865196273 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -568,6 +568,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // number if ("Integer".equals(datatype) || "Float".equals(datatype)) { String varName = name; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 03327dc9cd7..1b2e6686ad3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -513,6 +513,10 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index f29de4f66bd..c3430a63700 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -388,6 +388,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("static-method") public String toSwiftyEnumName(String value) { + if (value.length() == 0) { + return "Empty"; + } + if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number value = "Number" + value; value = value.replaceAll("-", "Minus"); diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 5809cb33122..0303e6bbec6 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1067,6 +1067,7 @@ definitions: enum: - UPPER - lower + - '' enum_integer: type: integer format: int32 diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs index b486563bcaa..6d901c80999 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -46,7 +46,13 @@ namespace IO.Swagger.Model /// Enum Lower for "lower" ///
    [EnumMember(Value = "lower")] - Lower + Lower, + + /// + /// Enum Empty for "" + /// + [EnumMember(Value = "")] + Empty } /// diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs index b4e8247da55..792a6c0356d 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs @@ -49,7 +49,13 @@ namespace IO.Swagger.Model /// Enum Lower for "lower" /// [EnumMember(Value = "lower")] - Lower + Lower, + + /// + /// Enum Empty for "" + /// + [EnumMember(Value = "")] + Empty } /// diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey1/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey1/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey1/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md index deb1951c552..29b6d288c8f 100644 --- a/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md @@ -15,6 +15,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java index c57488dbf7b..efa77302887 100644 --- a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java @@ -42,7 +42,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2/docs/EnumTest.md b/samples/client/petstore/java/jersey2/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey2/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md index deb1951c552..29b6d288c8f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md @@ -15,6 +15,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java index ce94e934b17..1932e9539f5 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java @@ -45,7 +45,10 @@ public class EnumTest implements Parcelable { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java index f0da7fb482c..38fa33789f3 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2/docs/EnumTest.md b/samples/client/petstore/java/retrofit2/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/javascript-promise/docs/EnumTest.md b/samples/client/petstore/javascript-promise/docs/EnumTest.md index c907dac4951..9d85a20016d 100644 --- a/samples/client/petstore/javascript-promise/docs/EnumTest.md +++ b/samples/client/petstore/javascript-promise/docs/EnumTest.md @@ -17,6 +17,8 @@ Name | Type | Description | Notes * `lower` (value: `"lower"`) +* `empty` (value: `""`) + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumTest.js b/samples/client/petstore/javascript-promise/src/model/EnumTest.js index 077ebcd470b..e33dd2c1186 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumTest.js @@ -111,7 +111,12 @@ * value: "lower" * @const */ - "lower": "lower" }; + "lower": "lower", + /** + * value: "" + * @const + */ + "empty": "" }; /** * Allowed values for the enum_integer property. diff --git a/samples/client/petstore/javascript/docs/EnumTest.md b/samples/client/petstore/javascript/docs/EnumTest.md index c907dac4951..9d85a20016d 100644 --- a/samples/client/petstore/javascript/docs/EnumTest.md +++ b/samples/client/petstore/javascript/docs/EnumTest.md @@ -17,6 +17,8 @@ Name | Type | Description | Notes * `lower` (value: `"lower"`) +* `empty` (value: `""`) + diff --git a/samples/client/petstore/javascript/src/model/EnumTest.js b/samples/client/petstore/javascript/src/model/EnumTest.js index 077ebcd470b..e33dd2c1186 100644 --- a/samples/client/petstore/javascript/src/model/EnumTest.js +++ b/samples/client/petstore/javascript/src/model/EnumTest.js @@ -111,7 +111,12 @@ * value: "lower" * @const */ - "lower": "lower" }; + "lower": "lower", + /** + * value: "" + * @const + */ + "empty": "" }; /** * Allowed values for the enum_integer property. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index cfee4f5eaab..20278d59053 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -118,6 +118,7 @@ class EnumTest implements ArrayAccess const ENUM_STRING_UPPER = 'UPPER'; const ENUM_STRING_LOWER = 'lower'; + const ENUM_STRING_EMPTY = ''; const ENUM_INTEGER_1 = 1; const ENUM_INTEGER_MINUS_1 = -1; const ENUM_NUMBER_1_DOT_1 = 1.1; @@ -134,6 +135,7 @@ class EnumTest implements ArrayAccess return [ self::ENUM_STRING_UPPER, self::ENUM_STRING_LOWER, + self::ENUM_STRING_EMPTY, ]; } @@ -188,7 +190,7 @@ class EnumTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; - $allowed_values = ["UPPER", "lower"]; + $allowed_values = ["UPPER", "lower", ""]; if (!in_array($this->container['enum_string'], $allowed_values)) { $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; } @@ -214,7 +216,7 @@ class EnumTest implements ArrayAccess */ public function valid() { - $allowed_values = ["UPPER", "lower"]; + $allowed_values = ["UPPER", "lower", ""]; if (!in_array($this->container['enum_string'], $allowed_values)) { return false; } @@ -246,9 +248,9 @@ class EnumTest implements ArrayAccess */ public function setEnumString($enum_string) { - $allowed_values = array('UPPER', 'lower'); + $allowed_values = array('UPPER', 'lower', ''); if (!is_null($enum_string) && (!in_array($enum_string, $allowed_values))) { - throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower'"); + throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower', ''"); } $this->container['enum_string'] = $enum_string; diff --git a/samples/client/petstore/python/petstore_api/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py index 2769128794a..d46d145dfaf 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -67,7 +67,7 @@ class EnumTest(object): :param enum_string: The enum_string of this EnumTest. :type: str """ - allowed_values = ["UPPER", "lower"] + allowed_values = ["UPPER", "lower", ""] if enum_string not in allowed_values: raise ValueError( "Invalid value for `enum_string` ({0}), must be one of {1}" diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index d8efd0acd22..c57cac73b59 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -100,7 +100,7 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) return false unless enum_string_validator.valid?(@enum_string) enum_integer_validator = EnumAttributeValidator.new('Integer', ["1", "-1"]) return false unless enum_integer_validator.valid?(@enum_integer) @@ -112,7 +112,7 @@ module Petstore # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_string Object to be assigned def enum_string=(enum_string) - validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) unless validator.valid?(enum_string) fail ArgumentError, "invalid value for 'enum_string', must be one of #{validator.allowable_values}." end diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java index 02fa4fc2283..9a0c2fb6107 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java @@ -19,7 +19,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml index 118ca53356a..cef4a8e8100 100644 --- a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml @@ -1100,6 +1100,7 @@ definitions: enum: - "UPPER" - "lower" + - "" enum_integer: type: "integer" format: "int32" diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java index 446649217c8..dc00d569c7e 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java @@ -18,7 +18,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..b68b0d79f3b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..b68b0d79f3b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java index 446649217c8..dc00d569c7e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java @@ -18,7 +18,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java index 446649217c8..dc00d569c7e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java @@ -18,7 +18,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java index 446649217c8..dc00d569c7e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java @@ -18,7 +18,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; From c0f1716fe79e190fe2da83b1d102821f4799be34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20Rodrigo?= Date: Fri, 6 Jan 2017 12:40:06 +0100 Subject: [PATCH 216/269] [html2] Open the description field that contains the description and required switch, in place of only show the field type by default (#4489) --- .../main/resources/htmlDocs2/param.mustache | 2 +- samples/html2/index.html | 38 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache index 69cf16352ca..2591e8aabfd 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache @@ -10,7 +10,7 @@ - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_{{nickname}}_{{paramName}}'); result.empty(); result.append(view.render()); diff --git a/samples/html2/index.html b/samples/html2/index.html index 42de47c06d2..ef49082d8d7 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -1446,7 +1446,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deletePet_petId'); result.empty(); result.append(view.render()); @@ -1486,7 +1486,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deletePet_apiKey'); result.empty(); result.append(view.render()); @@ -1738,7 +1738,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_findPetsByStatus_status'); result.empty(); result.append(view.render()); @@ -2030,7 +2030,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_findPetsByTags_tags'); result.empty(); result.append(view.render()); @@ -2325,7 +2325,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getPetById_petId'); result.empty(); result.append(view.render()); @@ -2873,7 +2873,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_petId'); result.empty(); result.append(view.render()); @@ -2916,7 +2916,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_name'); result.empty(); result.append(view.render()); @@ -2949,7 +2949,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_status'); result.empty(); result.append(view.render()); @@ -3206,7 +3206,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_petId'); result.empty(); result.append(view.render()); @@ -3249,7 +3249,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_additionalMetadata'); result.empty(); result.append(view.render()); @@ -3282,7 +3282,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_file'); result.empty(); result.append(view.render()); @@ -3538,7 +3538,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deleteOrder_orderId'); result.empty(); result.append(view.render()); @@ -4014,7 +4014,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getOrderById_orderId'); result.empty(); result.append(view.render()); @@ -5235,7 +5235,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deleteUser_username'); result.empty(); result.append(view.render()); @@ -5459,7 +5459,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getUserByName_username'); result.empty(); result.append(view.render()); @@ -5737,7 +5737,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_loginUser_username'); result.empty(); result.append(view.render()); @@ -5770,7 +5770,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_loginUser_password'); result.empty(); result.append(view.render()); @@ -6210,7 +6210,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updateUser_username'); result.empty(); result.append(view.render()); @@ -6303,7 +6303,7 @@ try {
    - Generated 2017-01-03T10:36:42.650-08:00 + Generated 2017-01-04T12:09:28.510+01:00
    From 5686109cc929e729ca8328801ebae3e52a18ebad Mon Sep 17 00:00:00 2001 From: JasonNorth Date: Fri, 6 Jan 2017 11:57:29 +0000 Subject: [PATCH 217/269] Allow templates to use maxItems and minItems for Arrays (#4309) Issue 3925 --- .../java/io/swagger/codegen/CodegenProperty.java | 13 ++++++++++++- .../java/io/swagger/codegen/DefaultCodegen.java | 2 ++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 4e6b9f8b879..5318d779e5b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -49,7 +49,10 @@ public class CodegenProperty implements Cloneable { public boolean isInherited; public String nameInCamelCase; // property name in camel case // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1) - public String enumName; + public String enumName; + public Integer maxItems; + public Integer minItems; + @Override public String toString() { @@ -117,6 +120,8 @@ public class CodegenProperty implements Cloneable { result = prime * result + Objects.hashCode(isInherited); result = prime * result + Objects.hashCode(nameInCamelCase); result = prime * result + Objects.hashCode(enumName); + result = prime * result + ((maxItems == null) ? 0 : maxItems.hashCode()); + result = prime * result + ((minItems == null) ? 0 : minItems.hashCode()); return result; } @@ -283,6 +288,12 @@ public class CodegenProperty implements Cloneable { if (!Objects.equals(this.enumName, other.enumName)) { return false; } + if (this.maxItems != other.maxItems && (this.maxItems == null || !this.maxItems.equals(other.maxItems))) { + return false; + } + if (this.minItems != other.minItems && (this.minItems == null || !this.minItems.equals(other.minItems))) { + return false; + } return true; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index a6d2d2ffe06..3c9c970af2a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1691,6 +1691,8 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); // handle inner property ArrayProperty ap = (ArrayProperty) p; + property.maxItems = ap.getMaxItems(); + property.minItems = ap.getMinItems(); CodegenProperty cp = fromProperty(property.name, ap.getItems()); updatePropertyForArray(property, cp); } else if (p instanceof MapProperty) { From dde24eb9c2e8d19392fd31ac64c972011e700077 Mon Sep 17 00:00:00 2001 From: "J. Fiala" Date: Fri, 6 Jan 2017 15:10:40 +0100 Subject: [PATCH 218/269] update jaxrs jersey1 templates and sample output #4091 --- .../JavaJaxRS/beanValidation.mustache | 82 +- .../libraries/jersey1/apiService.mustache | 62 +- .../libraries/jersey1/apiServiceImpl.mustache | 70 +- .../gen/java/io/swagger/api/ApiException.java | 20 +- .../java/io/swagger/api/ApiOriginFilter.java | 42 +- .../io/swagger/api/ApiResponseMessage.java | 138 ++-- .../src/gen/java/io/swagger/api/FakeApi.java | 201 ++--- .../java/io/swagger/api/FakeApiService.java | 62 +- .../io/swagger/api/JacksonJsonProvider.java | 52 +- .../io/swagger/api/NotFoundException.java | 20 +- .../src/gen/java/io/swagger/api/PetApi.java | 385 +++++---- .../java/io/swagger/api/PetApiService.java | 81 +- .../io/swagger/api/RFC3339DateFormat.java | 36 +- .../src/gen/java/io/swagger/api/StoreApi.java | 188 ++--- .../java/io/swagger/api/StoreApiService.java | 64 +- .../gen/java/io/swagger/api/StringUtil.java | 84 +- .../src/gen/java/io/swagger/api/UserApi.java | 294 +++---- .../java/io/swagger/api/UserApiService.java | 80 +- .../model/AdditionalPropertiesClass.java | 249 +++--- .../src/gen/java/io/swagger/model/Animal.java | 226 ++--- .../gen/java/io/swagger/model/AnimalFarm.java | 129 +-- .../model/ArrayOfArrayOfNumberOnly.java | 193 ++--- .../io/swagger/model/ArrayOfNumberOnly.java | 193 ++--- .../gen/java/io/swagger/model/ArrayTest.java | 305 +++---- .../src/gen/java/io/swagger/model/Cat.java | 181 +++-- .../gen/java/io/swagger/model/Category.java | 224 ++--- .../gen/java/io/swagger/model/ClassModel.java | 90 ++ .../src/gen/java/io/swagger/model/Client.java | 177 ++-- .../src/gen/java/io/swagger/model/Dog.java | 181 +++-- .../gen/java/io/swagger/model/EnumArrays.java | 363 ++++----- .../gen/java/io/swagger/model/EnumClass.java | 107 +-- .../gen/java/io/swagger/model/EnumTest.java | 481 +++++------ .../gen/java/io/swagger/model/FormatTest.java | 769 +++++++++--------- .../io/swagger/model/HasOnlyReadOnly.java | 187 ++--- .../gen/java/io/swagger/model/MapTest.java | 313 +++---- ...ropertiesAndAdditionalPropertiesClass.java | 289 +++---- .../io/swagger/model/Model200Response.java | 225 ++--- .../io/swagger/model/ModelApiResponse.java | 269 +++--- .../java/io/swagger/model/ModelReturn.java | 179 ++-- .../src/gen/java/io/swagger/model/Name.java | 282 +++---- .../gen/java/io/swagger/model/NumberOnly.java | 179 ++-- .../src/gen/java/io/swagger/model/Order.java | 478 +++++------ .../gen/java/io/swagger/model/OuterEnum.java | 54 ++ .../src/gen/java/io/swagger/model/Pet.java | 508 ++++++------ .../java/io/swagger/model/ReadOnlyFirst.java | 205 ++--- .../io/swagger/model/SpecialModelName.java | 177 ++-- .../src/gen/java/io/swagger/model/Tag.java | 224 ++--- .../src/gen/java/io/swagger/model/User.java | 500 ++++++------ .../api/factories/FakeApiServiceFactory.java | 26 +- .../api/factories/PetApiServiceFactory.java | 26 +- .../api/factories/StoreApiServiceFactory.java | 26 +- .../api/factories/UserApiServiceFactory.java | 26 +- .../swagger/api/impl/FakeApiServiceImpl.java | 86 +- .../swagger/api/impl/PetApiServiceImpl.java | 145 ++-- .../swagger/api/impl/StoreApiServiceImpl.java | 96 +-- .../swagger/api/impl/UserApiServiceImpl.java | 144 ++-- 56 files changed, 5344 insertions(+), 5129 deletions(-) create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache index f13ed596859..a4443e0fe5f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache @@ -1,42 +1,42 @@ -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minItems}} -{{#maxItems}} - @Size(min={{minItems}},max={{maxItems}}) -{{/maxItems}} -{{/minItems}} -{{#minItems}} -{{^maxItems}} - @Size(min={{minItems}}) -{{/maxItems}} -{{/minItems}} -{{^minItems}} -{{#maxItems}} - @Size(max={{maxItems}}) - {{/maxItems}} - {{/minItems}} -{{#minimum}} - @Min({{minimum}}) -{{/minimum}} -{{#maximum}} - @Max({{maximum}}) +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) + {{/maxItems}} + {{/minItems}} +{{#minimum}} +// @Min({{minimum}}) +{{/minimum}} +{{#maximum}} +// @Max({{maximum}}) {{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache index 2cc7b8c1fec..e1936698d02 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache @@ -1,30 +1,32 @@ -package {{package}}; - -import {{package}}.*; -import {{modelPackage}}.*; - -import com.sun.jersey.multipart.FormDataParam; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - -{{>generatedAnnotation}} -{{#operations}} -public abstract class {{classname}}Service { - {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) - throws NotFoundException; - {{/operation}} -} -{{/operations}} +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) + throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache index f4c558e7b11..ac7c6096b24 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache @@ -1,34 +1,36 @@ -package {{package}}.impl; - -import {{package}}.*; -import {{modelPackage}}.*; - -import com.sun.jersey.multipart.FormDataParam; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - -{{>generatedAnnotation}} -{{#operations}} -public class {{classname}}ServiceImpl extends {{classname}}Service { - {{#operation}} - @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - {{/operation}} -} -{{/operations}} +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java index 97e535d3c21..bde6ef86a6c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiException.java @@ -1,10 +1,10 @@ -package io.swagger.api; - - -public class ApiException extends Exception{ - private int code; - public ApiException (int code, String msg) { - super(msg); - this.code = code; - } -} +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java index 38791eef046..9a6035cd034 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -1,22 +1,22 @@ -package io.swagger.api; - -import java.io.IOException; - -import javax.servlet.*; -import javax.servlet.http.HttpServletResponse; - - -public class ApiOriginFilter implements javax.servlet.Filter { - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - HttpServletResponse res = (HttpServletResponse) response; - res.addHeader("Access-Control-Allow-Origin", "*"); - res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - res.addHeader("Access-Control-Allow-Headers", "Content-Type"); - chain.doFilter(request, response); - } - - public void destroy() {} - - public void init(FilterConfig filterConfig) throws ServletException {} +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() {} + + public void init(FilterConfig filterConfig) throws ServletException {} } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java index 87db95c1009..f692b9682df 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -1,69 +1,69 @@ -package io.swagger.api; - -import javax.xml.bind.annotation.XmlTransient; - -@javax.xml.bind.annotation.XmlRootElement - -public class ApiResponseMessage { - public static final int ERROR = 1; - public static final int WARNING = 2; - public static final int INFO = 3; - public static final int OK = 4; - public static final int TOO_BUSY = 5; - - int code; - String type; - String message; - - public ApiResponseMessage(){} - - public ApiResponseMessage(int code, String message){ - this.code = code; - switch(code){ - case ERROR: - setType("error"); - break; - case WARNING: - setType("warning"); - break; - case INFO: - setType("info"); - break; - case OK: - setType("ok"); - break; - case TOO_BUSY: - setType("too busy"); - break; - default: - setType("unknown"); - break; - } - this.message = message; - } - - @XmlTransient - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement + +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java index 64e951703be..712f08eacbf 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java @@ -1,100 +1,101 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.FakeApiService; -import io.swagger.api.factories.FakeApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/fake") - - -@io.swagger.annotations.Api(description = "the fake API") - -public class FakeApi { - private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); - - @PATCH - - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - public Response testClientModel( - @ApiParam(value = "client model" ,required=true) Client body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testClientModel(body,securityContext); - } - @POST - - @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) - @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) - @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "http_basic_test") - }, tags={ "fake", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response testEndpointParameters( - @ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number, - @ApiParam(value = "None", required=true) @FormParam("double") Double _double, - @ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter, - @ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte, - @ApiParam(value = "None") @FormParam("integer") Integer integer, - @ApiParam(value = "None") @FormParam("int32") Integer int32, - @ApiParam(value = "None") @FormParam("int64") Long int64, - @ApiParam(value = "None") @FormParam("float") Float _float, - @ApiParam(value = "None") @FormParam("string") String string, - @ApiParam(value = "None") @FormParam("binary") byte[] binary, - @ApiParam(value = "None") @FormParam("date") Date date, - @ApiParam(value = "None") @FormParam("dateTime") Date dateTime, - @ApiParam(value = "None") @FormParam("password") String password, - @ApiParam(value = "None") @FormParam("callback") String paramCallback, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,paramCallback,securityContext); - } - @GET - - @Consumes({ "*/*" }) - @Produces({ "*/*" }) - @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) - public Response testEnumParameters( - @ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray, - @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString, - @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray, - @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger, - @ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.FakeApiService; +import io.swagger.api.factories.FakeApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/fake") + + +@io.swagger.annotations.Api(description = "the fake API") + +public class FakeApi { + private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel( + @ApiParam(value = "client model" ,required=true) Client body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testClientModel(body,securityContext); + } + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters( + @ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number, + @ApiParam(value = "None", required=true) @FormParam("double") Double _double, + @ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter, + @ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte, + @ApiParam(value = "None") @FormParam("integer") Integer integer, + @ApiParam(value = "None") @FormParam("int32") Integer int32, + @ApiParam(value = "None") @FormParam("int64") Long int64, + @ApiParam(value = "None") @FormParam("float") Float _float, + @ApiParam(value = "None") @FormParam("string") String string, + @ApiParam(value = "None") @FormParam("binary") byte[] binary, + @ApiParam(value = "None") @FormParam("date") Date date, + @ApiParam(value = "None") @FormParam("dateTime") Date dateTime, + @ApiParam(value = "None") @FormParam("password") String password, + @ApiParam(value = "None") @FormParam("callback") String paramCallback, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,paramCallback,securityContext); + } + @GET + + @Consumes({ "*/*" }) + @Produces({ "*/*" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters( + @ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java index dd9726d60fc..247c18519b9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java @@ -1,31 +1,31 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class FakeApiService { - public abstract Response testClientModel(Client body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) - throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java index f476187ce3f..098023ed53c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -1,27 +1,27 @@ -package io.swagger.api; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.joda.JodaModule; -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; - -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.ext.Provider; - -@Provider -@Produces({MediaType.APPLICATION_JSON}) -public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - - public JacksonJsonProvider() { - - ObjectMapper objectMapper = new ObjectMapper() - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .registerModule(new JodaModule()) - .setDateFormat(new RFC3339DateFormat()); - - setMapper(objectMapper); - } +package io.swagger.api; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + + public JacksonJsonProvider() { + + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(new JodaModule()) + .setDateFormat(new RFC3339DateFormat()); + + setMapper(objectMapper); + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java index b28b67ea4b2..d24d1f0b24f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,10 +1,10 @@ -package io.swagger.api; - - -public class NotFoundException extends ApiException { - private int code; - public NotFoundException (int code, String msg) { - super(code, msg); - this.code = code; - } -} +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 263d332e048..1d11fa4b6dd 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -1,194 +1,191 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.PetApiService; -import io.swagger.api.factories.PetApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import com.sun.jersey.multipart.FormDataParam; -import javax.validation.constraints.*; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/pet") - - -@io.swagger.annotations.Api(description = "the pet API") - -public class PetApi { - private final PetApiService delegate = PetApiServiceFactory.getPetApi(); - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet( - @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.addPet(body,securityContext); - } - @DELETE - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet( - @ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId, - @ApiParam(value = "" )@HeaderParam("api_key") String apiKey, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deletePet(petId,apiKey,securityContext); - } - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus( - @ApiParam(value = "Status values that need to be considered for filter", allowableValues="available, pending, sold", defaultValue="available") @DefaultValue("available") @QueryParam("status") List status, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByStatus(status,securityContext); - } - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags( - @ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByTags(tags,securityContext); - } - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }), - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById( - @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetById(petId,securityContext); - } - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet( - @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePet(body,securityContext); - } - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm( - @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String petId, - @ApiParam(value = "Updated name of the pet") @FormParam("name") String name, - @ApiParam(value = "Updated status of the pet") @FormParam("status") String status, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status,securityContext); - } - @POST - @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response uploadFile( - @ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, - @FormDataParam("additionalMetadata") String additionalMetadata, - @FormDataParam("file") InputStream inputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/pet") + + +@io.swagger.annotations.Api(description = "the pet API") + +public class PetApi { + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet( + @ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.addPet(body,securityContext); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet( + @ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "" )@HeaderParam("api_key") String apiKey, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deletePet(petId,apiKey,securityContext); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus( + @ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags( + @ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById( + @ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet( + @ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm( + @ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId, + @ApiParam(value = "Updated name of the pet") @FormParam("name") String name, + @ApiParam(value = "Updated status of the pet") @FormParam("status") String status, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile( + @ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, + @FormDataParam("additionalMetadata") String additionalMetadata, + @FormDataParam("file") InputStream inputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.uploadFile(petId,additionalMetadata,inputStream, fileDetail,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index 255d31f3e4f..de4c7a63456 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -1,40 +1,41 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class PetApiService { - public abstract Response addPet(Pet body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) - throws NotFoundException; - public abstract Response findPetsByStatus( List status,SecurityContext securityContext) - throws NotFoundException; - public abstract Response findPetsByTags( List tags,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getPetById(Long petId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updatePet(Pet body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) - throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class PetApiService { + public abstract Response addPet(Pet body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) + throws NotFoundException; + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) + throws NotFoundException; + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getPetById(Long petId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response updatePet(Pet body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) + throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java index 7c9e260509e..729f238066c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -1,19 +1,19 @@ -package io.swagger.api; - -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; - -import java.text.FieldPosition; -import java.util.Date; - -public class RFC3339DateFormat extends ISO8601DateFormat { - - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } - +package io.swagger.api; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java index f6cbbe50ec4..e189d667231 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java @@ -1,94 +1,94 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.StoreApiService; -import io.swagger.api.factories.StoreApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import com.sun.jersey.multipart.FormDataParam; -import javax.validation.constraints.*; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/store") - - -@io.swagger.annotations.Api(description = "the store API") - -public class StoreApi { - private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); - - @DELETE - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder( - @ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteOrder(orderId,securityContext); - } - @GET - @Path("/inventory") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) - public Response getInventory( - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getInventory(securityContext); - } - @GET - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById( - @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getOrderById(orderId,securityContext); - } - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder( - @ApiParam(value = "order placed for purchasing the pet" ) Order body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.placeOrder(body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/store") + + +@io.swagger.annotations.Api(description = "the store API") + +public class StoreApi { + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder( + @ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory( + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById( + @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder( + @ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java index 9b5dde7d40e..6fe4971ffa0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java @@ -1,32 +1,32 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class StoreApiService { - public abstract Response deleteOrder(String orderId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getInventory(SecurityContext securityContext) - throws NotFoundException; - public abstract Response getOrderById(String orderId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response placeOrder(Order body,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class StoreApiService { + public abstract Response deleteOrder( @Min(1)String orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) + throws NotFoundException; + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java index 6f4a3dadbbf..11535a24384 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StringUtil.java @@ -1,42 +1,42 @@ -package io.swagger.api; - - -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(); - } -} +package io.swagger.api; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

    + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java index 5ecfdd9b9ea..1cc8f912281 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java @@ -1,147 +1,147 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.UserApiService; -import io.swagger.api.factories.UserApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import com.sun.jersey.multipart.FormDataParam; -import javax.validation.constraints.*; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/user") - - -@io.swagger.annotations.Api(description = "the user API") - -public class UserApi { - private final UserApiService delegate = UserApiServiceFactory.getUserApi(); - - @POST - - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser( - @ApiParam(value = "Created user object" ) User body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUser(body,securityContext); - } - @POST - @Path("/createWithArray") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput( - @ApiParam(value = "List of user object" ) List body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithArrayInput(body,securityContext); - } - @POST - @Path("/createWithList") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput( - @ApiParam(value = "List of user object" ) List body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithListInput(body,securityContext); - } - @DELETE - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser( - @ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteUser(username,securityContext); - } - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName( - @ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getUserByName(username,securityContext); - } - @GET - @Path("/login") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser( - @ApiParam(value = "The user name for login") @QueryParam("username") String username, - @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.loginUser(username,password,securityContext); - } - @GET - @Path("/logout") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response logoutUser( - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.logoutUser(securityContext); - } - @PUT - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser( - @ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, - @ApiParam(value = "Updated user object" ) User body, - @Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updateUser(username,body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; + +@Path("/user") + + +@io.swagger.annotations.Api(description = "the user API") + +public class UserApi { + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser( + @ApiParam(value = "Created user object" ,required=true) User body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUser(body,securityContext); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput( + @ApiParam(value = "List of user object" ,required=true) List body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithArrayInput(body,securityContext); + } + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput( + @ApiParam(value = "List of user object" ,required=true) List body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithListInput(body,securityContext); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser( + @ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName( + @ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser( + @ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username, + @ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser( + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser( + @ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username, + @ApiParam(value = "Updated user object" ,required=true) User body, + @Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updateUser(username,body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java index 97482052000..7c739c6890b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java @@ -1,40 +1,40 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class UserApiService { - public abstract Response createUser(User body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response loginUser( String username, String password,SecurityContext securityContext) - throws NotFoundException; - public abstract Response logoutUser(SecurityContext securityContext) - throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class UserApiService { + public abstract Response createUser(User body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getUserByName(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) + throws NotFoundException; + public abstract Response logoutUser(SecurityContext securityContext) + throws NotFoundException; + public abstract Response updateUser(String username,User body,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 55d1d0c5e45..74983fe3b61 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -1,124 +1,125 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * AdditionalPropertiesClass - */ - -public class AdditionalPropertiesClass { - @JsonProperty("map_property") - private Map mapProperty = new HashMap(); - - @JsonProperty("map_of_map_property") - private Map> mapOfMapProperty = new HashMap>(); - - public AdditionalPropertiesClass mapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - return this; - } - - public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { - this.mapProperty.put(key, mapPropertyItem); - return this; - } - - /** - * Get mapProperty - * @return mapProperty - **/ - @ApiModelProperty(value = "") - public Map getMapProperty() { - return mapProperty; - } - - public void setMapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - } - - public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - return this; - } - - public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { - this.mapOfMapProperty.put(key, mapOfMapPropertyItem); - return this; - } - - /** - * Get mapOfMapProperty - * @return mapOfMapProperty - **/ - @ApiModelProperty(value = "") - public Map> getMapOfMapProperty() { - return mapOfMapProperty; - } - - public void setMapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); - } - - @Override - public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AdditionalPropertiesClass {\n"); - - sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); - sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java index ae2b64e8c67..90e56088420 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java @@ -1,111 +1,115 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Animal - */ - -public class Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - - public Animal className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Animal color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className) && - Objects.equals(this.color, animal.color); - } - - @Override - public int hashCode() { - return Objects.hash(className, color); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Animal {\n"); - - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Animal + */ + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java index ed9baa7a24a..a3986d474c9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java @@ -1,64 +1,65 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import io.swagger.model.Animal; -import java.util.ArrayList; -import java.util.List; - -/** - * AnimalFarm - */ - -public class AnimalFarm extends ArrayList { - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - return true; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AnimalFarm {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 31be0acd0bd..10c0a4db84f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -1,96 +1,97 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayOfArrayOfNumberOnly - */ - -public class ArrayOfArrayOfNumberOnly { - @JsonProperty("ArrayArrayNumber") - private List> arrayArrayNumber = new ArrayList>(); - - public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - return this; - } - - public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { - this.arrayArrayNumber.add(arrayArrayNumberItem); - return this; - } - - /** - * Get arrayArrayNumber - * @return arrayArrayNumber - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayNumber() { - return arrayArrayNumber; - } - - public void setArrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayArrayNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfArrayOfNumberOnly {\n"); - - sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 1923213cce9..9baae5b46dc 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -1,96 +1,97 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayOfNumberOnly - */ - -public class ArrayOfNumberOnly { - @JsonProperty("ArrayNumber") - private List arrayNumber = new ArrayList(); - - public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - return this; - } - - public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { - this.arrayNumber.add(arrayNumberItem); - return this; - } - - /** - * Get arrayNumber - * @return arrayNumber - **/ - @ApiModelProperty(value = "") - public List getArrayNumber() { - return arrayNumber; - } - - public void setArrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfNumberOnly {\n"); - - sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java index ff6ed5937a5..bcd2b1a17d7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java @@ -1,152 +1,153 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.ReadOnlyFirst; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayTest - */ - -public class ArrayTest { - @JsonProperty("array_of_string") - private List arrayOfString = new ArrayList(); - - @JsonProperty("array_array_of_integer") - private List> arrayArrayOfInteger = new ArrayList>(); - - @JsonProperty("array_array_of_model") - private List> arrayArrayOfModel = new ArrayList>(); - - public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - return this; - } - - public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { - this.arrayOfString.add(arrayOfStringItem); - return this; - } - - /** - * Get arrayOfString - * @return arrayOfString - **/ - @ApiModelProperty(value = "") - public List getArrayOfString() { - return arrayOfString; - } - - public void setArrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - } - - public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - return this; - } - - public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { - this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); - return this; - } - - /** - * Get arrayArrayOfInteger - * @return arrayArrayOfInteger - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfInteger() { - return arrayArrayOfInteger; - } - - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - } - - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - return this; - } - - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { - this.arrayArrayOfModel.add(arrayArrayOfModelItem); - return this; - } - - /** - * Get arrayArrayOfModel - * @return arrayArrayOfModel - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfModel() { - return arrayArrayOfModel; - } - - public void setArrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && - Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); - } - - @Override - public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayTest {\n"); - - sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); - sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); - sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java index 7fbae697738..4b344e857c9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java @@ -1,90 +1,91 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; - -/** - * Cat - */ - -public class Cat extends Animal { - @JsonProperty("declawed") - private Boolean declawed = null; - - public Cat declawed(Boolean declawed) { - this.declawed = declawed; - return this; - } - - /** - * Get declawed - * @return declawed - **/ - @ApiModelProperty(value = "") - public Boolean getDeclawed() { - return declawed; - } - - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Cat cat = (Cat) o; - return Objects.equals(this.declawed, cat.declawed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(declawed, super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java index 9d5452ac70c..f6c40fb71ac 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -1,112 +1,112 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * Category - */ - -public class Category { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("name") - private String name = null; - - public Category id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Category name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Category category = (Category) o; - return Objects.equals(this.id, category.id) && - Objects.equals(this.name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..bf476fcddcd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java index ad56b48eeb9..4f026c26a3a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java @@ -1,88 +1,89 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Client - */ - -public class Client { - @JsonProperty("client") - private String client = null; - - public Client client(String client) { - this.client = client; - return this; - } - - /** - * Get client - * @return client - **/ - @ApiModelProperty(value = "") - public String getClient() { - return client; - } - - public void setClient(String client) { - this.client = client; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Client client = (Client) o; - return Objects.equals(this.client, client.client); - } - - @Override - public int hashCode() { - return Objects.hash(client); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Client {\n"); - - sb.append(" client: ").append(toIndentedString(client)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java index ca6dc1c3af7..fa32e834b5d 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java @@ -1,90 +1,91 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; - -/** - * Dog - */ - -public class Dog extends Animal { - @JsonProperty("breed") - private String breed = null; - - public Dog breed(String breed) { - this.breed = breed; - return this; - } - - /** - * Get breed - * @return breed - **/ - @ApiModelProperty(value = "") - public String getBreed() { - return breed; - } - - public void setBreed(String breed) { - this.breed = breed; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Dog dog = (Dog) o; - return Objects.equals(this.breed, dog.breed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(breed, super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java index 55feec29353..cb5f2675e9b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java @@ -1,181 +1,182 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; - -/** - * EnumArrays - */ - -public class EnumArrays { - /** - * Gets or Sets justSymbol - */ - public enum JustSymbolEnum { - GREATER_THAN_OR_EQUAL_TO(">="), - - DOLLAR("$"); - - private String value; - - JustSymbolEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static JustSymbolEnum fromValue(String text) { - for (JustSymbolEnum b : JustSymbolEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("just_symbol") - private JustSymbolEnum justSymbol = null; - - /** - * Gets or Sets arrayEnum - */ - public enum ArrayEnumEnum { - FISH("fish"), - - CRAB("crab"); - - private String value; - - ArrayEnumEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static ArrayEnumEnum fromValue(String text) { - for (ArrayEnumEnum b : ArrayEnumEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("array_enum") - private List arrayEnum = new ArrayList(); - - public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - return this; - } - - /** - * Get justSymbol - * @return justSymbol - **/ - @ApiModelProperty(value = "") - public JustSymbolEnum getJustSymbol() { - return justSymbol; - } - - public void setJustSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - } - - public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - return this; - } - - public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { - this.arrayEnum.add(arrayEnumItem); - return this; - } - - /** - * Get arrayEnum - * @return arrayEnum - **/ - @ApiModelProperty(value = "") - public List getArrayEnum() { - return arrayEnum; - } - - public void setArrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(this.justSymbol, enumArrays.justSymbol) && - Objects.equals(this.arrayEnum, enumArrays.arrayEnum); - } - - @Override - public int hashCode() { - return Objects.hash(justSymbol, arrayEnum); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumArrays {\n"); - - sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); - sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java index cc4b2108ee9..92f7514a4c3 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java @@ -1,53 +1,54 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; - -import com.fasterxml.jackson.annotation.JsonCreator; - -/** - * Gets or Sets EnumClass - */ -public enum EnumClass { - - _ABC("_abc"), - - _EFG("-efg"), - - _XYZ_("(xyz)"); - - private String value; - - EnumClass(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumClass fromValue(String text) { - for (EnumClass b : EnumClass.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..79825c5c4da 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java @@ -1,228 +1,253 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * EnumTest - */ - -public class EnumTest { - /** - * Gets or Sets enumString - */ - public enum EnumStringEnum { - UPPER("UPPER"), - - LOWER("lower"); - - private String value; - - EnumStringEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumStringEnum fromValue(String text) { - for (EnumStringEnum b : EnumStringEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_string") - private EnumStringEnum enumString = null; - - /** - * Gets or Sets enumInteger - */ - public enum EnumIntegerEnum { - NUMBER_1(1), - - NUMBER_MINUS_1(-1); - - private Integer value; - - EnumIntegerEnum(Integer value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumIntegerEnum fromValue(String text) { - for (EnumIntegerEnum b : EnumIntegerEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_integer") - private EnumIntegerEnum enumInteger = null; - - /** - * Gets or Sets enumNumber - */ - public enum EnumNumberEnum { - NUMBER_1_DOT_1(1.1), - - NUMBER_MINUS_1_DOT_2(-1.2); - - private Double value; - - EnumNumberEnum(Double value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumNumberEnum fromValue(String text) { - for (EnumNumberEnum b : EnumNumberEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_number") - private EnumNumberEnum enumNumber = null; - - public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; - return this; - } - - /** - * Get enumString - * @return enumString - **/ - @ApiModelProperty(value = "") - public EnumStringEnum getEnumString() { - return enumString; - } - - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - return this; - } - - /** - * Get enumInteger - * @return enumInteger - **/ - @ApiModelProperty(value = "") - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - return this; - } - - /** - * Get enumNumber - * @return enumNumber - **/ - @ApiModelProperty(value = "") - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumTest enumTest = (EnumTest) o; - return Objects.equals(this.enumString, enumTest.enumString) && - Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java index 203c4a105d8..e7a6b6584f7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -1,376 +1,393 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.Date; - -/** - * FormatTest - */ - -public class FormatTest { - @JsonProperty("integer") - private Integer integer = null; - - @JsonProperty("int32") - private Integer int32 = null; - - @JsonProperty("int64") - private Long int64 = null; - - @JsonProperty("number") - private BigDecimal number = null; - - @JsonProperty("float") - private Float _float = null; - - @JsonProperty("double") - private Double _double = null; - - @JsonProperty("string") - private String string = null; - - @JsonProperty("byte") - private byte[] _byte = null; - - @JsonProperty("binary") - private byte[] binary = null; - - @JsonProperty("date") - private Date date = null; - - @JsonProperty("dateTime") - private Date dateTime = null; - - @JsonProperty("uuid") - private String uuid = null; - - @JsonProperty("password") - private String password = null; - - public FormatTest integer(Integer integer) { - this.integer = integer; - return this; - } - - /** - * Get integer - * minimum: 10.0 - * maximum: 100.0 - * @return integer - **/ - @ApiModelProperty(value = "") - public Integer getInteger() { - return integer; - } - - public void setInteger(Integer integer) { - this.integer = integer; - } - - public FormatTest int32(Integer int32) { - this.int32 = int32; - return this; - } - - /** - * Get int32 - * minimum: 20.0 - * maximum: 200.0 - * @return int32 - **/ - @ApiModelProperty(value = "") - public Integer getInt32() { - return int32; - } - - public void setInt32(Integer int32) { - this.int32 = int32; - } - - public FormatTest int64(Long int64) { - this.int64 = int64; - return this; - } - - /** - * Get int64 - * @return int64 - **/ - @ApiModelProperty(value = "") - public Long getInt64() { - return int64; - } - - public void setInt64(Long int64) { - this.int64 = int64; - } - - public FormatTest number(BigDecimal number) { - this.number = number; - return this; - } - - /** - * Get number - * minimum: 32.1 - * maximum: 543.2 - * @return number - **/ - @ApiModelProperty(required = true, value = "") - public BigDecimal getNumber() { - return number; - } - - public void setNumber(BigDecimal number) { - this.number = number; - } - - public FormatTest _float(Float _float) { - this._float = _float; - return this; - } - - /** - * Get _float - * minimum: 54.3 - * maximum: 987.6 - * @return _float - **/ - @ApiModelProperty(value = "") - public Float getFloat() { - return _float; - } - - public void setFloat(Float _float) { - this._float = _float; - } - - public FormatTest _double(Double _double) { - this._double = _double; - return this; - } - - /** - * Get _double - * minimum: 67.8 - * maximum: 123.4 - * @return _double - **/ - @ApiModelProperty(value = "") - public Double getDouble() { - return _double; - } - - public void setDouble(Double _double) { - this._double = _double; - } - - public FormatTest string(String string) { - this.string = string; - return this; - } - - /** - * Get string - * @return string - **/ - @ApiModelProperty(value = "") - public String getString() { - return string; - } - - public void setString(String string) { - this.string = string; - } - - public FormatTest _byte(byte[] _byte) { - this._byte = _byte; - return this; - } - - /** - * Get _byte - * @return _byte - **/ - @ApiModelProperty(required = true, value = "") - public byte[] getByte() { - return _byte; - } - - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - public FormatTest binary(byte[] binary) { - this.binary = binary; - return this; - } - - /** - * Get binary - * @return binary - **/ - @ApiModelProperty(value = "") - public byte[] getBinary() { - return binary; - } - - public void setBinary(byte[] binary) { - this.binary = binary; - } - - public FormatTest date(Date date) { - this.date = date; - return this; - } - - /** - * Get date - * @return date - **/ - @ApiModelProperty(required = true, value = "") - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public FormatTest dateTime(Date dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public FormatTest uuid(String uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public FormatTest password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @ApiModelProperty(required = true, value = "") - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FormatTest formatTest = (FormatTest) o; - return Objects.equals(this.integer, formatTest.integer) && - Objects.equals(this.int32, formatTest.int32) && - Objects.equals(this.int64, formatTest.int64) && - Objects.equals(this.number, formatTest.number) && - Objects.equals(this._float, formatTest._float) && - Objects.equals(this._double, formatTest._double) && - Objects.equals(this.string, formatTest.string) && - Objects.equals(this._byte, formatTest._byte) && - Objects.equals(this.binary, formatTest.binary) && - Objects.equals(this.date, formatTest.date) && - Objects.equals(this.dateTime, formatTest.dateTime) && - Objects.equals(this.uuid, formatTest.uuid) && - Objects.equals(this.password, formatTest.password); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FormatTest {\n"); - - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; +import javax.validation.constraints.*; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") +// @Min(10) +// @Max(100) + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") +// @Min(20) +// @Max(200) + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + @NotNull +// @Min(32.1) +// @Max(543.2) + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") +// @Min(54.3) +// @Max(987.6) + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") +// @Min(67.8) +// @Max(123.4) + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(Date date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 73611bc43e0..bcc6487e630 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -1,93 +1,94 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * HasOnlyReadOnly - */ - -public class HasOnlyReadOnly { - @JsonProperty("bar") - private String bar = null; - - @JsonProperty("foo") - private String foo = null; - - /** - * Get bar - * @return bar - **/ - @ApiModelProperty(value = "") - public String getBar() { - return bar; - } - - /** - * Get foo - * @return foo - **/ - @ApiModelProperty(value = "") - public String getFoo() { - return foo; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(this.bar, hasOnlyReadOnly.bar) && - Objects.equals(this.foo, hasOnlyReadOnly.foo); - } - - @Override - public int hashCode() { - return Objects.hash(bar, foo); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HasOnlyReadOnly {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java index 58037229c3e..9a6b68d03a7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java @@ -1,156 +1,157 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * MapTest - */ - -public class MapTest { - @JsonProperty("map_map_of_string") - private Map> mapMapOfString = new HashMap>(); - - /** - * Gets or Sets inner - */ - public enum InnerEnum { - UPPER("UPPER"), - - LOWER("lower"); - - private String value; - - InnerEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static InnerEnum fromValue(String text) { - for (InnerEnum b : InnerEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("map_of_enum_string") - private Map mapOfEnumString = new HashMap(); - - public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - return this; - } - - public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { - this.mapMapOfString.put(key, mapMapOfStringItem); - return this; - } - - /** - * Get mapMapOfString - * @return mapMapOfString - **/ - @ApiModelProperty(value = "") - public Map> getMapMapOfString() { - return mapMapOfString; - } - - public void setMapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - } - - public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - return this; - } - - public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { - this.mapOfEnumString.put(key, mapOfEnumStringItem); - return this; - } - - /** - * Get mapOfEnumString - * @return mapOfEnumString - **/ - @ApiModelProperty(value = "") - public Map getMapOfEnumString() { - return mapOfEnumString; - } - - public void setMapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MapTest mapTest = (MapTest) o; - return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); - } - - @Override - public int hashCode() { - return Objects.hash(mapMapOfString, mapOfEnumString); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MapTest {\n"); - - sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); - sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d9c75346f4d..2ee96c79560 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,144 +1,145 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * MixedPropertiesAndAdditionalPropertiesClass - */ - -public class MixedPropertiesAndAdditionalPropertiesClass { - @JsonProperty("uuid") - private String uuid = null; - - @JsonProperty("dateTime") - private Date dateTime = null; - - @JsonProperty("map") - private Map map = new HashMap(); - - public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; - return this; - } - - public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { - this.map.put(key, mapItem); - return this; - } - - /** - * Get map - * @return map - **/ - @ApiModelProperty(value = "") - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, dateTime, map); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" map: ").append(toIndentedString(map)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java index 78c6e9c7e93..f84b190bdac 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java @@ -1,112 +1,113 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing model name starting with number - */ -@ApiModel(description = "Model for testing model name starting with number") - -public class Model200Response { - @JsonProperty("name") - private Integer name = null; - - @JsonProperty("class") - private String propertyClass = null; - - public Model200Response name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public Integer getName() { - return name; - } - - public void setName(Integer name) { - this.name = name; - } - - public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; - return this; - } - - /** - * Get propertyClass - * @return propertyClass - **/ - @ApiModelProperty(value = "") - public String getPropertyClass() { - return propertyClass; - } - - public void setPropertyClass(String propertyClass) { - this.propertyClass = propertyClass; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Model200Response _200Response = (Model200Response) o; - return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.propertyClass, _200Response.propertyClass); - } - - @Override - public int hashCode() { - return Objects.hash(name, propertyClass); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Model200Response {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java index c80ea613b76..8f66f1ae0a0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,134 +1,135 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * ModelApiResponse - */ - -public class ModelApiResponse { - @JsonProperty("code") - private Integer code = null; - - @JsonProperty("type") - private String type = null; - - @JsonProperty("message") - private String message = null; - - public ModelApiResponse code(Integer code) { - this.code = code; - return this; - } - - /** - * Get code - * @return code - **/ - @ApiModelProperty(value = "") - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - public ModelApiResponse type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - **/ - @ApiModelProperty(value = "") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public ModelApiResponse message(String message) { - this.message = message; - return this; - } - - /** - * Get message - * @return message - **/ - @ApiModelProperty(value = "") - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(this.code, _apiResponse.code) && - Objects.equals(this.type, _apiResponse.type) && - Objects.equals(this.message, _apiResponse.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelApiResponse {\n"); - - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java index 7907a3fd186..aba2654d739 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java @@ -1,89 +1,90 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing reserved words - */ -@ApiModel(description = "Model for testing reserved words") - -public class ModelReturn { - @JsonProperty("return") - private Integer _return = null; - - public ModelReturn _return(Integer _return) { - this._return = _return; - return this; - } - - /** - * Get _return - * @return _return - **/ - @ApiModelProperty(value = "") - public Integer getReturn() { - return _return; - } - - public void setReturn(Integer _return) { - this._return = _return; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelReturn _return = (ModelReturn) o; - return Objects.equals(this._return, _return._return); - } - - @Override - public int hashCode() { - return Objects.hash(_return); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelReturn {\n"); - - sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java index b9ffac6e40d..b81443ca6eb 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java @@ -1,140 +1,142 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing model name same as property name - */ -@ApiModel(description = "Model for testing model name same as property name") - -public class Name { - @JsonProperty("name") - private Integer name = null; - - @JsonProperty("snake_case") - private Integer snakeCase = null; - - @JsonProperty("property") - private String property = null; - - @JsonProperty("123Number") - private Integer _123Number = null; - - public Name name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(required = true, value = "") - public Integer getName() { - return name; - } - - public void setName(Integer name) { - this.name = name; - } - - /** - * Get snakeCase - * @return snakeCase - **/ - @ApiModelProperty(value = "") - public Integer getSnakeCase() { - return snakeCase; - } - - public Name property(String property) { - this.property = property; - return this; - } - - /** - * Get property - * @return property - **/ - @ApiModelProperty(value = "") - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } - - /** - * Get _123Number - * @return _123Number - **/ - @ApiModelProperty(value = "") - public Integer get123Number() { - return _123Number; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Name name = (Name) o; - return Objects.equals(this.name, name.name) && - Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property) && - Objects.equals(this._123Number, name._123Number); - } - - @Override - public int hashCode() { - return Objects.hash(name, snakeCase, property, _123Number); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Name {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); - sb.append(" property: ").append(toIndentedString(property)).append("\n"); - sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java index a3333adbce0..31847afc70c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java @@ -1,89 +1,90 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; - -/** - * NumberOnly - */ - -public class NumberOnly { - @JsonProperty("JustNumber") - private BigDecimal justNumber = null; - - public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - return this; - } - - /** - * Get justNumber - * @return justNumber - **/ - @ApiModelProperty(value = "") - public BigDecimal getJustNumber() { - return justNumber; - } - - public void setJustNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(this.justNumber, numberOnly.justNumber); - } - - @Override - public int hashCode() { - return Objects.hash(justNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class NumberOnly {\n"); - - sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java index c37f8f4334c..182f4c8298a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java @@ -1,239 +1,239 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.Date; -import javax.validation.constraints.*; - -/** - * Order - */ - -public class Order { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("petId") - private Long petId = null; - - @JsonProperty("quantity") - private Integer quantity = null; - - @JsonProperty("shipDate") - private Date shipDate = null; - - /** - * Order Status - */ - public enum StatusEnum { - PLACED("placed"), - - APPROVED("approved"), - - DELIVERED("delivered"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String text) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("status") - private StatusEnum status = null; - - @JsonProperty("complete") - private Boolean complete = null; - - public Order id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Order petId(Long petId) { - this.petId = petId; - return this; - } - - /** - * Get petId - * @return petId - **/ - @ApiModelProperty(value = "") - public Long getPetId() { - return petId; - } - - public void setPetId(Long petId) { - this.petId = petId; - } - - public Order quantity(Integer quantity) { - this.quantity = quantity; - return this; - } - - /** - * Get quantity - * @return quantity - **/ - @ApiModelProperty(value = "") - public Integer getQuantity() { - return quantity; - } - - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - public Order shipDate(Date shipDate) { - this.shipDate = shipDate; - return this; - } - - /** - * Get shipDate - * @return shipDate - **/ - @ApiModelProperty(value = "") - public Date getShipDate() { - return shipDate; - } - - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - public Order status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * Order Status - * @return status - **/ - @ApiModelProperty(value = "Order Status") - public StatusEnum getStatus() { - return status; - } - - public void setStatus(StatusEnum status) { - this.status = status; - } - - public Order complete(Boolean complete) { - this.complete = complete; - return this; - } - - /** - * Get complete - * @return complete - **/ - @ApiModelProperty(value = "") - public Boolean getComplete() { - return complete; - } - - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && - Objects.equals(this.petId, order.petId) && - Objects.equals(this.quantity, order.quantity) && - Objects.equals(this.shipDate, order.shipDate) && - Objects.equals(this.status, order.status) && - Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; +import javax.validation.constraints.*; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private Date shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..8adbba83671 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index a12394dabce..df945003380 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -1,254 +1,254 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Category; -import io.swagger.model.Tag; -import java.util.ArrayList; -import java.util.List; -import javax.validation.constraints.*; - -/** - * Pet - */ - -public class Pet { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("category") - private Category category = null; - - @JsonProperty("name") - private String name = null; - - @JsonProperty("photoUrls") - private List photoUrls = new ArrayList(); - - @JsonProperty("tags") - private List tags = new ArrayList(); - - /** - * pet status in the store - */ - public enum StatusEnum { - AVAILABLE("available"), - - PENDING("pending"), - - SOLD("sold"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String text) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("status") - private StatusEnum status = null; - - public Pet id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Pet category(Category category) { - this.category = category; - return this; - } - - /** - * Get category - * @return category - **/ - @ApiModelProperty(value = "") - public Category getCategory() { - return category; - } - - public void setCategory(Category category) { - this.category = category; - } - - public Pet name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(example = "doggie", required = true, value = "") - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; - return this; - } - - public Pet addPhotoUrlsItem(String photoUrlsItem) { - this.photoUrls.add(photoUrlsItem); - return this; - } - - /** - * Get photoUrls - * @return photoUrls - **/ - @ApiModelProperty(required = true, value = "") - @NotNull - public List getPhotoUrls() { - return photoUrls; - } - - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - public Pet tags(List tags) { - this.tags = tags; - return this; - } - - public Pet addTagsItem(Tag tagsItem) { - this.tags.add(tagsItem); - return this; - } - - /** - * Get tags - * @return tags - **/ - @ApiModelProperty(value = "") - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public Pet status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * pet status in the store - * @return status - **/ - @ApiModelProperty(value = "pet status in the store") - public StatusEnum getStatus() { - return status; - } - - public void setStatus(StatusEnum status) { - this.status = status; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Pet pet = (Pet) o; - return Objects.equals(this.id, pet.id) && - Objects.equals(this.category, pet.category) && - Objects.equals(this.name, pet.name) && - Objects.equals(this.photoUrls, pet.photoUrls) && - Objects.equals(this.tags, pet.tags) && - Objects.equals(this.status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 8ce60288125..d5399b10a4a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -1,102 +1,103 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * ReadOnlyFirst - */ - -public class ReadOnlyFirst { - @JsonProperty("bar") - private String bar = null; - - @JsonProperty("baz") - private String baz = null; - - /** - * Get bar - * @return bar - **/ - @ApiModelProperty(value = "") - public String getBar() { - return bar; - } - - public ReadOnlyFirst baz(String baz) { - this.baz = baz; - return this; - } - - /** - * Get baz - * @return baz - **/ - @ApiModelProperty(value = "") - public String getBaz() { - return baz; - } - - public void setBaz(String baz) { - this.baz = baz; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(this.bar, readOnlyFirst.bar) && - Objects.equals(this.baz, readOnlyFirst.baz); - } - - @Override - public int hashCode() { - return Objects.hash(bar, baz); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ReadOnlyFirst {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java index a32ef45986a..80ebc22cbc4 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java @@ -1,88 +1,89 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * SpecialModelName - */ - -public class SpecialModelName { - @JsonProperty("$special[property.name]") - private Long specialPropertyName = null; - - public SpecialModelName specialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - return this; - } - - /** - * Get specialPropertyName - * @return specialPropertyName - **/ - @ApiModelProperty(value = "") - public Long getSpecialPropertyName() { - return specialPropertyName; - } - - public void setSpecialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); - } - - @Override - public int hashCode() { - return Objects.hash(specialPropertyName); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SpecialModelName {\n"); - - sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java index 27bce18c966..1587c557c40 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -1,112 +1,112 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * Tag - */ - -public class Tag { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("name") - private String name = null; - - public Tag id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Tag name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Tag tag = (Tag) o; - return Objects.equals(this.id, tag.id) && - Objects.equals(this.name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java index 700b1165976..c1c6353056c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -1,250 +1,250 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * User - */ - -public class User { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("username") - private String username = null; - - @JsonProperty("firstName") - private String firstName = null; - - @JsonProperty("lastName") - private String lastName = null; - - @JsonProperty("email") - private String email = null; - - @JsonProperty("password") - private String password = null; - - @JsonProperty("phone") - private String phone = null; - - @JsonProperty("userStatus") - private Integer userStatus = null; - - public User id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public User username(String username) { - this.username = username; - return this; - } - - /** - * Get username - * @return username - **/ - @ApiModelProperty(value = "") - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public User firstName(String firstName) { - this.firstName = firstName; - return this; - } - - /** - * Get firstName - * @return firstName - **/ - @ApiModelProperty(value = "") - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public User lastName(String lastName) { - this.lastName = lastName; - return this; - } - - /** - * Get lastName - * @return lastName - **/ - @ApiModelProperty(value = "") - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public User email(String email) { - this.email = email; - return this; - } - - /** - * Get email - * @return email - **/ - @ApiModelProperty(value = "") - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public User password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @ApiModelProperty(value = "") - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public User phone(String phone) { - this.phone = phone; - return this; - } - - /** - * Get phone - * @return phone - **/ - @ApiModelProperty(value = "") - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public User userStatus(Integer userStatus) { - this.userStatus = userStatus; - return this; - } - - /** - * User Status - * @return userStatus - **/ - @ApiModelProperty(value = "User Status") - public Integer getUserStatus() { - return userStatus; - } - - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return Objects.equals(this.id, user.id) && - Objects.equals(this.username, user.username) && - Objects.equals(this.firstName, user.firstName) && - Objects.equals(this.lastName, user.lastName) && - Objects.equals(this.email, user.email) && - Objects.equals(this.password, user.password) && - Objects.equals(this.phone, user.phone) && - Objects.equals(this.userStatus, user.userStatus); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java index d4f8e013671..2cdfed7a93a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.FakeApiService; -import io.swagger.api.impl.FakeApiServiceImpl; - - -public class FakeApiServiceFactory { - private final static FakeApiService service = new FakeApiServiceImpl(); - - public static FakeApiService getFakeApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.FakeApiService; +import io.swagger.api.impl.FakeApiServiceImpl; + + +public class FakeApiServiceFactory { + private final static FakeApiService service = new FakeApiServiceImpl(); + + public static FakeApiService getFakeApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index 43321e8c0e9..648305ae936 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.PetApiService; -import io.swagger.api.impl.PetApiServiceImpl; - - -public class PetApiServiceFactory { - private final static PetApiService service = new PetApiServiceImpl(); - - public static PetApiService getPetApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.PetApiService; +import io.swagger.api.impl.PetApiServiceImpl; + + +public class PetApiServiceFactory { + private final static PetApiService service = new PetApiServiceImpl(); + + public static PetApiService getPetApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 254fd0a9a7d..b26a4ad0faf 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.StoreApiService; -import io.swagger.api.impl.StoreApiServiceImpl; - - -public class StoreApiServiceFactory { - private final static StoreApiService service = new StoreApiServiceImpl(); - - public static StoreApiService getStoreApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.StoreApiService; +import io.swagger.api.impl.StoreApiServiceImpl; + + +public class StoreApiServiceFactory { + private final static StoreApiService service = new StoreApiServiceImpl(); + + public static StoreApiService getStoreApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 4c50105bb50..13e3d0c190f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.UserApiService; -import io.swagger.api.impl.UserApiServiceImpl; - - -public class UserApiServiceFactory { - private final static UserApiService service = new UserApiServiceImpl(); - - public static UserApiService getUserApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.UserApiService; +import io.swagger.api.impl.UserApiServiceImpl; + + +public class UserApiServiceFactory { + private final static UserApiService service = new UserApiServiceImpl(); + + public static UserApiService getUserApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index a5d85fa89e8..9b37ce040ba 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -1,43 +1,43 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class FakeApiServiceImpl extends FakeApiService { - @Override - public Response testClientModel(Client body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 2802343d2a1..689b00c86b2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,72 +1,73 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class PetApiServiceImpl extends PetApiService { - @Override - public Response addPet(Pet body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByStatus( List status, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByTags( List tags, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getPetById(Long petId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePet(Pet body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePetWithForm(String petId, String name, String status, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class PetApiServiceImpl extends PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index e6f65e0958f..3c525974c49 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,48 +1,48 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class StoreApiServiceImpl extends StoreApiService { - @Override - public Response deleteOrder(String orderId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getInventory(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getOrderById(String orderId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response placeOrder(Order body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class StoreApiServiceImpl extends StoreApiService { + @Override + public Response deleteOrder( @Min(1)String orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 35a4ec4092b..6ac7fec7fba 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,72 +1,72 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class UserApiServiceImpl extends UserApiService { - @Override - public Response createUser(User body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deleteUser(String username, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getUserByName(String username, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response loginUser( String username, String password, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response logoutUser(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updateUser(String username, User body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class UserApiServiceImpl extends UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} From 5b532fd10ededc0ee802c1de304ed0e192fc8e40 Mon Sep 17 00:00:00 2001 From: "J. Fiala" Date: Fri, 6 Jan 2017 15:16:39 +0100 Subject: [PATCH 219/269] update language jaxrs (Jersey2) and samples --- .../resources/JavaJaxRS/apiService.mustache | 54 +- .../JavaJaxRS/apiServiceImpl.mustache | 62 +- .../gen/java/io/swagger/api/ApiException.java | 20 +- .../java/io/swagger/api/ApiOriginFilter.java | 42 +- .../io/swagger/api/ApiResponseMessage.java | 138 ++-- .../src/gen/java/io/swagger/api/FakeApi.java | 195 ++--- .../java/io/swagger/api/FakeApiService.java | 50 +- .../io/swagger/api/JacksonJsonProvider.java | 52 +- .../io/swagger/api/NotFoundException.java | 20 +- .../src/gen/java/io/swagger/api/PetApi.java | 379 +++++---- .../java/io/swagger/api/PetApiService.java | 59 +- .../io/swagger/api/RFC3339DateFormat.java | 36 +- .../src/gen/java/io/swagger/api/StoreApi.java | 184 ++--- .../java/io/swagger/api/StoreApiService.java | 50 +- .../gen/java/io/swagger/api/StringUtil.java | 84 +- .../src/gen/java/io/swagger/api/UserApi.java | 284 +++---- .../java/io/swagger/api/UserApiService.java | 58 +- .../model/AdditionalPropertiesClass.java | 249 +++--- .../src/gen/java/io/swagger/model/Animal.java | 226 ++--- .../gen/java/io/swagger/model/AnimalFarm.java | 129 +-- .../model/ArrayOfArrayOfNumberOnly.java | 193 ++--- .../io/swagger/model/ArrayOfNumberOnly.java | 193 ++--- .../gen/java/io/swagger/model/ArrayTest.java | 305 +++---- .../src/gen/java/io/swagger/model/Cat.java | 181 +++-- .../gen/java/io/swagger/model/Category.java | 224 ++--- .../gen/java/io/swagger/model/ClassModel.java | 90 ++ .../src/gen/java/io/swagger/model/Client.java | 177 ++-- .../src/gen/java/io/swagger/model/Dog.java | 181 +++-- .../gen/java/io/swagger/model/EnumArrays.java | 363 ++++----- .../gen/java/io/swagger/model/EnumClass.java | 107 +-- .../gen/java/io/swagger/model/EnumTest.java | 481 +++++------ .../gen/java/io/swagger/model/FormatTest.java | 769 +++++++++--------- .../io/swagger/model/HasOnlyReadOnly.java | 187 ++--- .../gen/java/io/swagger/model/MapTest.java | 313 +++---- ...ropertiesAndAdditionalPropertiesClass.java | 289 +++---- .../io/swagger/model/Model200Response.java | 225 ++--- .../io/swagger/model/ModelApiResponse.java | 269 +++--- .../java/io/swagger/model/ModelReturn.java | 179 ++-- .../src/gen/java/io/swagger/model/Name.java | 282 +++---- .../gen/java/io/swagger/model/NumberOnly.java | 179 ++-- .../src/gen/java/io/swagger/model/Order.java | 478 +++++------ .../gen/java/io/swagger/model/OuterEnum.java | 54 ++ .../src/gen/java/io/swagger/model/Pet.java | 508 ++++++------ .../java/io/swagger/model/ReadOnlyFirst.java | 205 ++--- .../io/swagger/model/SpecialModelName.java | 177 ++-- .../src/gen/java/io/swagger/model/Tag.java | 224 ++--- .../src/gen/java/io/swagger/model/User.java | 500 ++++++------ .../api/factories/FakeApiServiceFactory.java | 26 +- .../api/factories/PetApiServiceFactory.java | 26 +- .../api/factories/StoreApiServiceFactory.java | 26 +- .../api/factories/UserApiServiceFactory.java | 26 +- .../swagger/api/impl/FakeApiServiceImpl.java | 74 +- .../swagger/api/impl/PetApiServiceImpl.java | 123 +-- .../swagger/api/impl/StoreApiServiceImpl.java | 82 +- .../swagger/api/impl/UserApiServiceImpl.java | 122 +-- 55 files changed, 5212 insertions(+), 4997 deletions(-) create mode 100644 samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 50e00e24497..6fe60bcf862 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -1,26 +1,28 @@ -package {{package}}; - -import {{package}}.*; -import {{modelPackage}}.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - -{{>generatedAnnotation}} -{{#operations}} -public abstract class {{classname}}Service { - {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; - {{/operation}} -} -{{/operations}} +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 3d3f4c6cbf7..23adf05ec80 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -1,30 +1,32 @@ -package {{package}}.impl; - -import {{package}}.*; -import {{modelPackage}}.*; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - -{{>generatedAnnotation}} -{{#operations}} -public class {{classname}}ServiceImpl extends {{classname}}Service { - {{#operation}} - @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - {{/operation}} -} -{{/operations}} +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java index 97e535d3c21..bde6ef86a6c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiException.java @@ -1,10 +1,10 @@ -package io.swagger.api; - - -public class ApiException extends Exception{ - private int code; - public ApiException (int code, String msg) { - super(msg); - this.code = code; - } -} +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java index 38791eef046..9a6035cd034 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -1,22 +1,22 @@ -package io.swagger.api; - -import java.io.IOException; - -import javax.servlet.*; -import javax.servlet.http.HttpServletResponse; - - -public class ApiOriginFilter implements javax.servlet.Filter { - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain chain) throws IOException, ServletException { - HttpServletResponse res = (HttpServletResponse) response; - res.addHeader("Access-Control-Allow-Origin", "*"); - res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); - res.addHeader("Access-Control-Allow-Headers", "Content-Type"); - chain.doFilter(request, response); - } - - public void destroy() {} - - public void init(FilterConfig filterConfig) throws ServletException {} +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + public void destroy() {} + + public void init(FilterConfig filterConfig) throws ServletException {} } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java index 87db95c1009..f692b9682df 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -1,69 +1,69 @@ -package io.swagger.api; - -import javax.xml.bind.annotation.XmlTransient; - -@javax.xml.bind.annotation.XmlRootElement - -public class ApiResponseMessage { - public static final int ERROR = 1; - public static final int WARNING = 2; - public static final int INFO = 3; - public static final int OK = 4; - public static final int TOO_BUSY = 5; - - int code; - String type; - String message; - - public ApiResponseMessage(){} - - public ApiResponseMessage(int code, String message){ - this.code = code; - switch(code){ - case ERROR: - setType("error"); - break; - case WARNING: - setType("warning"); - break; - case INFO: - setType("info"); - break; - case OK: - setType("ok"); - break; - case TOO_BUSY: - setType("too busy"); - break; - default: - setType("unknown"); - break; - } - this.message = message; - } - - @XmlTransient - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement + +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java index a1e2db5e58a..9788c361774 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java @@ -1,97 +1,98 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.FakeApiService; -import io.swagger.api.factories.FakeApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; - -@Path("/fake") - - -@io.swagger.annotations.Api(description = "the fake API") - -public class FakeApi { - private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); - - @PATCH - - @Consumes({ "application/json" }) - @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - public Response testClientModel(@ApiParam(value = "client model" ,required=true) Client body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testClientModel(body,securityContext); - } - @POST - - @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) - @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) - @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "http_basic_test") - }, tags={ "fake", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response testEndpointParameters(@ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number -,@ApiParam(value = "None", required=true) @FormParam("double") Double _double -,@ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter -,@ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte -,@ApiParam(value = "None") @FormParam("integer") Integer integer -,@ApiParam(value = "None") @FormParam("int32") Integer int32 -,@ApiParam(value = "None") @FormParam("int64") Long int64 -,@ApiParam(value = "None") @FormParam("float") Float _float -,@ApiParam(value = "None") @FormParam("string") String string -,@ApiParam(value = "None") @FormParam("binary") byte[] binary -,@ApiParam(value = "None") @FormParam("date") Date date -,@ApiParam(value = "None") @FormParam("dateTime") Date dateTime -,@ApiParam(value = "None") @FormParam("password") String password -,@ApiParam(value = "None") @FormParam("callback") String paramCallback -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,paramCallback,securityContext); - } - @GET - - @Consumes({ "*/*" }) - @Produces({ "*/*" }) - @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) - public Response testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray -,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString -,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray -,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString -,@ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray -,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString -,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger -,@ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.FakeApiService; +import io.swagger.api.factories.FakeApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; +import javax.validation.constraints.*; + +@Path("/fake") + + +@io.swagger.annotations.Api(description = "the fake API") + +public class FakeApi { + private final FakeApiService delegate = FakeApiServiceFactory.getFakeApi(); + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel(@ApiParam(value = "client model" ,required=true) Client body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testClientModel(body,securityContext); + } + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @io.swagger.annotations.ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters(@ApiParam(value = "None", required=true) @FormParam("number") BigDecimal number +,@ApiParam(value = "None", required=true) @FormParam("double") Double _double +,@ApiParam(value = "None", required=true) @FormParam("pattern_without_delimiter") String patternWithoutDelimiter +,@ApiParam(value = "None", required=true) @FormParam("byte") byte[] _byte +,@ApiParam(value = "None") @FormParam("integer") Integer integer +,@ApiParam(value = "None") @FormParam("int32") Integer int32 +,@ApiParam(value = "None") @FormParam("int64") Long int64 +,@ApiParam(value = "None") @FormParam("float") Float _float +,@ApiParam(value = "None") @FormParam("string") String string +,@ApiParam(value = "None") @FormParam("binary") byte[] binary +,@ApiParam(value = "None") @FormParam("date") Date date +,@ApiParam(value = "None") @FormParam("dateTime") Date dateTime +,@ApiParam(value = "None") @FormParam("password") String password +,@ApiParam(value = "None") @FormParam("callback") String paramCallback +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEndpointParameters(number,_double,patternWithoutDelimiter,_byte,integer,int32,int64,_float,string,binary,date,dateTime,password,paramCallback,securityContext); + } + @GET + + @Consumes({ "*/*" }) + @Produces({ "*/*" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @FormParam("enum_form_string_array") List enumFormStringArray +,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString +,@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray +,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString +,@ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray +,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString +,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") Integer enumQueryInteger +,@ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testEnumParameters(enumFormStringArray,enumFormString,enumHeaderStringArray,enumHeaderString,enumQueryStringArray,enumQueryString,enumQueryInteger,enumQueryDouble,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java index 0109f9edc57..e49ec4c2d1c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java @@ -1,25 +1,25 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class FakeApiService { - public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java index f476187ce3f..098023ed53c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/JacksonJsonProvider.java @@ -1,27 +1,27 @@ -package io.swagger.api; - -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.joda.JodaModule; -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; - -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.ext.Provider; - -@Provider -@Produces({MediaType.APPLICATION_JSON}) -public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - - public JacksonJsonProvider() { - - ObjectMapper objectMapper = new ObjectMapper() - .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .registerModule(new JodaModule()) - .setDateFormat(new RFC3339DateFormat()); - - setMapper(objectMapper); - } +package io.swagger.api; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.joda.JodaModule; +import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; + +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.ext.Provider; + +@Provider +@Produces({MediaType.APPLICATION_JSON}) +public class JacksonJsonProvider extends JacksonJaxbJsonProvider { + + public JacksonJsonProvider() { + + ObjectMapper objectMapper = new ObjectMapper() + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .registerModule(new JodaModule()) + .setDateFormat(new RFC3339DateFormat()); + + setMapper(objectMapper); + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java index b28b67ea4b2..d24d1f0b24f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,10 +1,10 @@ -package io.swagger.api; - - -public class NotFoundException extends ApiException { - private int code; - public NotFoundException (int code, String msg) { - super(code, msg); - this.code = code; - } -} +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java index 430606b5f2e..b80cd88a9d8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -1,191 +1,188 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.PetApiService; -import io.swagger.api.factories.PetApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; -import javax.validation.constraints.*; - -@Path("/pet") - - -@io.swagger.annotations.Api(description = "the pet API") - -public class PetApi { - private final PetApiService delegate = PetApiServiceFactory.getPetApi(); - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.addPet(body,securityContext); - } - @DELETE - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId -,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deletePet(petId,apiKey,securityContext); - } - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", allowableValues="available, pending, sold", defaultValue="available") @DefaultValue("available") @QueryParam("status") List status -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByStatus(status,securityContext); - } - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.findPetsByTags(tags,securityContext); - } - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }), - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("petId") Long petId -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getPetById(petId,securityContext); - } - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePet(body,securityContext); - } - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") String petId -,@ApiParam(value = "Updated name of the pet") @FormParam("name") String name -,@ApiParam(value = "Updated status of the pet") @FormParam("status") String status -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status,securityContext); - } - @POST - @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { - @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") - }) - }, tags={ "pet", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId -,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata -, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileDetail -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,fileInputStream, fileDetail,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.PetApiService; +import io.swagger.api.factories.PetApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; +import javax.validation.constraints.*; + +@Path("/pet") + + +@io.swagger.annotations.Api(description = "the pet API") + +public class PetApi { + private final PetApiService delegate = PetApiServiceFactory.getPetApi(); + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.addPet(body,securityContext); + } + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deletePet(petId,apiKey,securityContext); + } + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByStatus(status,securityContext); + } + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.findPetsByTags(tags,securityContext); + } + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathParam("petId") Long petId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getPetById(petId,securityContext); + } + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePet(body,securityContext); + } + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Updated name of the pet") @FormParam("name") String name +,@ApiParam(value = "Updated status of the pet") @FormParam("status") String status +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updatePetWithForm(petId,name,status,securityContext); + } + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId +,@ApiParam(value = "Additional data to pass to server")@FormDataParam("additionalMetadata") String additionalMetadata +, + @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileDetail +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.uploadFile(petId,additionalMetadata,fileInputStream, fileDetail,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index b692895d979..8ac5692e507 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -1,29 +1,30 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class PetApiService { - public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus( List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags( List tags,SecurityContext securityContext) throws NotFoundException; - public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(String petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class PetApiService { + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) throws NotFoundException; + public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java index 7c9e260509e..729f238066c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/RFC3339DateFormat.java @@ -1,19 +1,19 @@ -package io.swagger.api; - -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; - -import java.text.FieldPosition; -import java.util.Date; - -public class RFC3339DateFormat extends ISO8601DateFormat { - - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } - +package io.swagger.api; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java index 56a5cf6ce36..83b75d8ab5a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -1,92 +1,92 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.StoreApiService; -import io.swagger.api.factories.StoreApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; -import javax.validation.constraints.*; - -@Path("/store") - - -@io.swagger.annotations.Api(description = "the store API") - -public class StoreApi { - private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); - - @DELETE - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteOrder(orderId,securityContext); - } - @GET - @Path("/inventory") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") - }, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) - public Response getInventory(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getInventory(securityContext); - } - @GET - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") String orderId -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getOrderById(orderId,securityContext); - } - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.placeOrder(body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.StoreApiService; +import io.swagger.api.factories.StoreApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; +import javax.validation.constraints.*; + +@Path("/store") + + +@io.swagger.annotations.Api(description = "the store API") + +public class StoreApi { + private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathParam("orderId") String orderId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteOrder(orderId,securityContext); + } + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getInventory(securityContext); + } + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getOrderById(orderId,securityContext); + } + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.placeOrder(body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java index 15cea4db0d3..139c1c45915 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -1,25 +1,25 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class StoreApiService { - public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(String orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class StoreApiService { + public abstract Response deleteOrder( @Min(1)String orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java index 6f4a3dadbbf..11535a24384 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StringUtil.java @@ -1,42 +1,42 @@ -package io.swagger.api; - - -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(); - } -} +package io.swagger.api; + + +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

    + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java index 5ccee5dca7a..3bddd139b26 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -1,142 +1,142 @@ -package io.swagger.api; - -import io.swagger.model.*; -import io.swagger.api.UserApiService; -import io.swagger.api.factories.UserApiServiceFactory; - -import io.swagger.annotations.ApiParam; -import io.swagger.jaxrs.*; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; - -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.ws.rs.*; -import javax.validation.constraints.*; - -@Path("/user") - - -@io.swagger.annotations.Api(description = "the user API") - -public class UserApi { - private final UserApiService delegate = UserApiServiceFactory.getUserApi(); - - @POST - - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser(@ApiParam(value = "Created user object" ) User body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUser(body,securityContext); - } - @POST - @Path("/createWithArray") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithArrayInput(body,securityContext); - } - @POST - @Path("/createWithList") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.createUsersWithListInput(body,securityContext); - } - @DELETE - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.deleteUser(username,securityContext); - } - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.getUserByName(username,securityContext); - } - @GET - @Path("/login") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), - - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username -,@ApiParam(value = "The password for login in clear text") @QueryParam("password") String password -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.loginUser(username,password,securityContext); - } - @GET - @Path("/logout") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response logoutUser(@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.logoutUser(securityContext); - } - @PUT - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), - - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username -,@ApiParam(value = "Updated user object" ) User body -,@Context SecurityContext securityContext) - throws NotFoundException { - return delegate.updateUser(username,body,securityContext); - } -} +package io.swagger.api; + +import io.swagger.model.*; +import io.swagger.api.UserApiService; +import io.swagger.api.factories.UserApiServiceFactory; + +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; + +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.ws.rs.*; +import javax.validation.constraints.*; + +@Path("/user") + + +@io.swagger.annotations.Api(description = "the user API") + +public class UserApi { + private final UserApiService delegate = UserApiServiceFactory.getUserApi(); + + @POST + + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUser(body,securityContext); + } + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithArrayInput(body,securityContext); + } + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.createUsersWithListInput(body,securityContext); + } + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.deleteUser(username,securityContext); + } + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true) @PathParam("username") String username +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.getUserByName(username,securityContext); + } + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), + + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username +,@ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.loginUser(username,password,securityContext); + } + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser(@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.logoutUser(securityContext); + } + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathParam("username") String username +,@ApiParam(value = "Updated user object" ,required=true) User body +,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.updateUser(username,body,securityContext); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java index 45375dff120..254895ec80b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -1,29 +1,29 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public abstract class UserApiService { - public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser( String username, String password,SecurityContext securityContext) throws NotFoundException; - public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class UserApiService { + public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; + public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; + public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 55d1d0c5e45..74983fe3b61 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -1,124 +1,125 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * AdditionalPropertiesClass - */ - -public class AdditionalPropertiesClass { - @JsonProperty("map_property") - private Map mapProperty = new HashMap(); - - @JsonProperty("map_of_map_property") - private Map> mapOfMapProperty = new HashMap>(); - - public AdditionalPropertiesClass mapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - return this; - } - - public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { - this.mapProperty.put(key, mapPropertyItem); - return this; - } - - /** - * Get mapProperty - * @return mapProperty - **/ - @ApiModelProperty(value = "") - public Map getMapProperty() { - return mapProperty; - } - - public void setMapProperty(Map mapProperty) { - this.mapProperty = mapProperty; - } - - public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - return this; - } - - public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { - this.mapOfMapProperty.put(key, mapOfMapPropertyItem); - return this; - } - - /** - * Get mapOfMapProperty - * @return mapOfMapProperty - **/ - @ApiModelProperty(value = "") - public Map> getMapOfMapProperty() { - return mapOfMapProperty; - } - - public void setMapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); - } - - @Override - public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AdditionalPropertiesClass {\n"); - - sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); - sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java index ae2b64e8c67..90e56088420 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -1,111 +1,115 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Animal - */ - -public class Animal { - @JsonProperty("className") - private String className = null; - - @JsonProperty("color") - private String color = "red"; - - public Animal className(String className) { - this.className = className; - return this; - } - - /** - * Get className - * @return className - **/ - @ApiModelProperty(required = true, value = "") - public String getClassName() { - return className; - } - - public void setClassName(String className) { - this.className = className; - } - - public Animal color(String color) { - this.color = color; - return this; - } - - /** - * Get color - * @return color - **/ - @ApiModelProperty(value = "") - public String getColor() { - return color; - } - - public void setColor(String color) { - this.color = color; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Animal animal = (Animal) o; - return Objects.equals(this.className, animal.className) && - Objects.equals(this.color, animal.color); - } - - @Override - public int hashCode() { - return Objects.hash(className, color); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Animal {\n"); - - sb.append(" className: ").append(toIndentedString(className)).append("\n"); - sb.append(" color: ").append(toIndentedString(color)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Animal + */ + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java index ed9baa7a24a..a3986d474c9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java @@ -1,64 +1,65 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import io.swagger.model.Animal; -import java.util.ArrayList; -import java.util.List; - -/** - * AnimalFarm - */ - -public class AnimalFarm extends ArrayList { - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - return true; - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class AnimalFarm {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 31be0acd0bd..10c0a4db84f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -1,96 +1,97 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayOfArrayOfNumberOnly - */ - -public class ArrayOfArrayOfNumberOnly { - @JsonProperty("ArrayArrayNumber") - private List> arrayArrayNumber = new ArrayList>(); - - public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - return this; - } - - public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { - this.arrayArrayNumber.add(arrayArrayNumberItem); - return this; - } - - /** - * Get arrayArrayNumber - * @return arrayArrayNumber - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayNumber() { - return arrayArrayNumber; - } - - public void setArrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayArrayNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfArrayOfNumberOnly {\n"); - - sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 1923213cce9..9baae5b46dc 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -1,96 +1,97 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayOfNumberOnly - */ - -public class ArrayOfNumberOnly { - @JsonProperty("ArrayNumber") - private List arrayNumber = new ArrayList(); - - public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - return this; - } - - public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { - this.arrayNumber.add(arrayNumberItem); - return this; - } - - /** - * Get arrayNumber - * @return arrayNumber - **/ - @ApiModelProperty(value = "") - public List getArrayNumber() { - return arrayNumber; - } - - public void setArrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); - } - - @Override - public int hashCode() { - return Objects.hash(arrayNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayOfNumberOnly {\n"); - - sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java index ff6ed5937a5..bcd2b1a17d7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java @@ -1,152 +1,153 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.ReadOnlyFirst; -import java.util.ArrayList; -import java.util.List; - -/** - * ArrayTest - */ - -public class ArrayTest { - @JsonProperty("array_of_string") - private List arrayOfString = new ArrayList(); - - @JsonProperty("array_array_of_integer") - private List> arrayArrayOfInteger = new ArrayList>(); - - @JsonProperty("array_array_of_model") - private List> arrayArrayOfModel = new ArrayList>(); - - public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - return this; - } - - public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { - this.arrayOfString.add(arrayOfStringItem); - return this; - } - - /** - * Get arrayOfString - * @return arrayOfString - **/ - @ApiModelProperty(value = "") - public List getArrayOfString() { - return arrayOfString; - } - - public void setArrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; - } - - public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - return this; - } - - public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { - this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); - return this; - } - - /** - * Get arrayArrayOfInteger - * @return arrayArrayOfInteger - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfInteger() { - return arrayArrayOfInteger; - } - - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; - } - - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - return this; - } - - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { - this.arrayArrayOfModel.add(arrayArrayOfModelItem); - return this; - } - - /** - * Get arrayArrayOfModel - * @return arrayArrayOfModel - **/ - @ApiModelProperty(value = "") - public List> getArrayArrayOfModel() { - return arrayArrayOfModel; - } - - public void setArrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && - Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); - } - - @Override - public int hashCode() { - return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ArrayTest {\n"); - - sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); - sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); - sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java index 7fbae697738..4b344e857c9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java @@ -1,90 +1,91 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; - -/** - * Cat - */ - -public class Cat extends Animal { - @JsonProperty("declawed") - private Boolean declawed = null; - - public Cat declawed(Boolean declawed) { - this.declawed = declawed; - return this; - } - - /** - * Get declawed - * @return declawed - **/ - @ApiModelProperty(value = "") - public Boolean getDeclawed() { - return declawed; - } - - public void setDeclawed(Boolean declawed) { - this.declawed = declawed; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Cat cat = (Cat) o; - return Objects.equals(this.declawed, cat.declawed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(declawed, super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Cat {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index 9d5452ac70c..f6c40fb71ac 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -1,112 +1,112 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * Category - */ - -public class Category { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("name") - private String name = null; - - public Category id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Category name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Category category = (Category) o; - return Objects.equals(this.id, category.id) && - Objects.equals(this.name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..bf476fcddcd --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java index ad56b48eeb9..4f026c26a3a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java @@ -1,88 +1,89 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Client - */ - -public class Client { - @JsonProperty("client") - private String client = null; - - public Client client(String client) { - this.client = client; - return this; - } - - /** - * Get client - * @return client - **/ - @ApiModelProperty(value = "") - public String getClient() { - return client; - } - - public void setClient(String client) { - this.client = client; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Client client = (Client) o; - return Objects.equals(this.client, client.client); - } - - @Override - public int hashCode() { - return Objects.hash(client); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Client {\n"); - - sb.append(" client: ").append(toIndentedString(client)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java index ca6dc1c3af7..fa32e834b5d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java @@ -1,90 +1,91 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; - -/** - * Dog - */ - -public class Dog extends Animal { - @JsonProperty("breed") - private String breed = null; - - public Dog breed(String breed) { - this.breed = breed; - return this; - } - - /** - * Get breed - * @return breed - **/ - @ApiModelProperty(value = "") - public String getBreed() { - return breed; - } - - public void setBreed(String breed) { - this.breed = breed; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Dog dog = (Dog) o; - return Objects.equals(this.breed, dog.breed) && - super.equals(o); - } - - @Override - public int hashCode() { - return Objects.hash(breed, super.hashCode()); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Dog {\n"); - sb.append(" ").append(toIndentedString(super.toString())).append("\n"); - sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java index 55feec29353..cb5f2675e9b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java @@ -1,181 +1,182 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.ArrayList; -import java.util.List; - -/** - * EnumArrays - */ - -public class EnumArrays { - /** - * Gets or Sets justSymbol - */ - public enum JustSymbolEnum { - GREATER_THAN_OR_EQUAL_TO(">="), - - DOLLAR("$"); - - private String value; - - JustSymbolEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static JustSymbolEnum fromValue(String text) { - for (JustSymbolEnum b : JustSymbolEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("just_symbol") - private JustSymbolEnum justSymbol = null; - - /** - * Gets or Sets arrayEnum - */ - public enum ArrayEnumEnum { - FISH("fish"), - - CRAB("crab"); - - private String value; - - ArrayEnumEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static ArrayEnumEnum fromValue(String text) { - for (ArrayEnumEnum b : ArrayEnumEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("array_enum") - private List arrayEnum = new ArrayList(); - - public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - return this; - } - - /** - * Get justSymbol - * @return justSymbol - **/ - @ApiModelProperty(value = "") - public JustSymbolEnum getJustSymbol() { - return justSymbol; - } - - public void setJustSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; - } - - public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - return this; - } - - public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { - this.arrayEnum.add(arrayEnumItem); - return this; - } - - /** - * Get arrayEnum - * @return arrayEnum - **/ - @ApiModelProperty(value = "") - public List getArrayEnum() { - return arrayEnum; - } - - public void setArrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(this.justSymbol, enumArrays.justSymbol) && - Objects.equals(this.arrayEnum, enumArrays.arrayEnum); - } - - @Override - public int hashCode() { - return Objects.hash(justSymbol, arrayEnum); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumArrays {\n"); - - sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); - sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java index cc4b2108ee9..92f7514a4c3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java @@ -1,53 +1,54 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonValue; - -import com.fasterxml.jackson.annotation.JsonCreator; - -/** - * Gets or Sets EnumClass - */ -public enum EnumClass { - - _ABC("_abc"), - - _EFG("-efg"), - - _XYZ_("(xyz)"); - - private String value; - - EnumClass(String value) { - this.value = value; - } - - @Override - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumClass fromValue(String text) { - for (EnumClass b : EnumClass.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..79825c5c4da 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -1,228 +1,253 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * EnumTest - */ - -public class EnumTest { - /** - * Gets or Sets enumString - */ - public enum EnumStringEnum { - UPPER("UPPER"), - - LOWER("lower"); - - private String value; - - EnumStringEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumStringEnum fromValue(String text) { - for (EnumStringEnum b : EnumStringEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_string") - private EnumStringEnum enumString = null; - - /** - * Gets or Sets enumInteger - */ - public enum EnumIntegerEnum { - NUMBER_1(1), - - NUMBER_MINUS_1(-1); - - private Integer value; - - EnumIntegerEnum(Integer value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumIntegerEnum fromValue(String text) { - for (EnumIntegerEnum b : EnumIntegerEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_integer") - private EnumIntegerEnum enumInteger = null; - - /** - * Gets or Sets enumNumber - */ - public enum EnumNumberEnum { - NUMBER_1_DOT_1(1.1), - - NUMBER_MINUS_1_DOT_2(-1.2); - - private Double value; - - EnumNumberEnum(Double value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static EnumNumberEnum fromValue(String text) { - for (EnumNumberEnum b : EnumNumberEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("enum_number") - private EnumNumberEnum enumNumber = null; - - public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; - return this; - } - - /** - * Get enumString - * @return enumString - **/ - @ApiModelProperty(value = "") - public EnumStringEnum getEnumString() { - return enumString; - } - - public void setEnumString(EnumStringEnum enumString) { - this.enumString = enumString; - } - - public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - return this; - } - - /** - * Get enumInteger - * @return enumInteger - **/ - @ApiModelProperty(value = "") - public EnumIntegerEnum getEnumInteger() { - return enumInteger; - } - - public void setEnumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; - } - - public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - return this; - } - - /** - * Get enumNumber - * @return enumNumber - **/ - @ApiModelProperty(value = "") - public EnumNumberEnum getEnumNumber() { - return enumNumber; - } - - public void setEnumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - EnumTest enumTest = (EnumTest) o; - return Objects.equals(this.enumString, enumTest.enumString) && - Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); - } - - @Override - public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class EnumTest {\n"); - - sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); - sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); - sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index 203c4a105d8..e7a6b6584f7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -1,376 +1,393 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; -import java.util.Date; - -/** - * FormatTest - */ - -public class FormatTest { - @JsonProperty("integer") - private Integer integer = null; - - @JsonProperty("int32") - private Integer int32 = null; - - @JsonProperty("int64") - private Long int64 = null; - - @JsonProperty("number") - private BigDecimal number = null; - - @JsonProperty("float") - private Float _float = null; - - @JsonProperty("double") - private Double _double = null; - - @JsonProperty("string") - private String string = null; - - @JsonProperty("byte") - private byte[] _byte = null; - - @JsonProperty("binary") - private byte[] binary = null; - - @JsonProperty("date") - private Date date = null; - - @JsonProperty("dateTime") - private Date dateTime = null; - - @JsonProperty("uuid") - private String uuid = null; - - @JsonProperty("password") - private String password = null; - - public FormatTest integer(Integer integer) { - this.integer = integer; - return this; - } - - /** - * Get integer - * minimum: 10.0 - * maximum: 100.0 - * @return integer - **/ - @ApiModelProperty(value = "") - public Integer getInteger() { - return integer; - } - - public void setInteger(Integer integer) { - this.integer = integer; - } - - public FormatTest int32(Integer int32) { - this.int32 = int32; - return this; - } - - /** - * Get int32 - * minimum: 20.0 - * maximum: 200.0 - * @return int32 - **/ - @ApiModelProperty(value = "") - public Integer getInt32() { - return int32; - } - - public void setInt32(Integer int32) { - this.int32 = int32; - } - - public FormatTest int64(Long int64) { - this.int64 = int64; - return this; - } - - /** - * Get int64 - * @return int64 - **/ - @ApiModelProperty(value = "") - public Long getInt64() { - return int64; - } - - public void setInt64(Long int64) { - this.int64 = int64; - } - - public FormatTest number(BigDecimal number) { - this.number = number; - return this; - } - - /** - * Get number - * minimum: 32.1 - * maximum: 543.2 - * @return number - **/ - @ApiModelProperty(required = true, value = "") - public BigDecimal getNumber() { - return number; - } - - public void setNumber(BigDecimal number) { - this.number = number; - } - - public FormatTest _float(Float _float) { - this._float = _float; - return this; - } - - /** - * Get _float - * minimum: 54.3 - * maximum: 987.6 - * @return _float - **/ - @ApiModelProperty(value = "") - public Float getFloat() { - return _float; - } - - public void setFloat(Float _float) { - this._float = _float; - } - - public FormatTest _double(Double _double) { - this._double = _double; - return this; - } - - /** - * Get _double - * minimum: 67.8 - * maximum: 123.4 - * @return _double - **/ - @ApiModelProperty(value = "") - public Double getDouble() { - return _double; - } - - public void setDouble(Double _double) { - this._double = _double; - } - - public FormatTest string(String string) { - this.string = string; - return this; - } - - /** - * Get string - * @return string - **/ - @ApiModelProperty(value = "") - public String getString() { - return string; - } - - public void setString(String string) { - this.string = string; - } - - public FormatTest _byte(byte[] _byte) { - this._byte = _byte; - return this; - } - - /** - * Get _byte - * @return _byte - **/ - @ApiModelProperty(required = true, value = "") - public byte[] getByte() { - return _byte; - } - - public void setByte(byte[] _byte) { - this._byte = _byte; - } - - public FormatTest binary(byte[] binary) { - this.binary = binary; - return this; - } - - /** - * Get binary - * @return binary - **/ - @ApiModelProperty(value = "") - public byte[] getBinary() { - return binary; - } - - public void setBinary(byte[] binary) { - this.binary = binary; - } - - public FormatTest date(Date date) { - this.date = date; - return this; - } - - /** - * Get date - * @return date - **/ - @ApiModelProperty(required = true, value = "") - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public FormatTest dateTime(Date dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public FormatTest uuid(String uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public FormatTest password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @ApiModelProperty(required = true, value = "") - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - FormatTest formatTest = (FormatTest) o; - return Objects.equals(this.integer, formatTest.integer) && - Objects.equals(this.int32, formatTest.int32) && - Objects.equals(this.int64, formatTest.int64) && - Objects.equals(this.number, formatTest.number) && - Objects.equals(this._float, formatTest._float) && - Objects.equals(this._double, formatTest._double) && - Objects.equals(this.string, formatTest.string) && - Objects.equals(this._byte, formatTest._byte) && - Objects.equals(this.binary, formatTest.binary) && - Objects.equals(this.date, formatTest.date) && - Objects.equals(this.dateTime, formatTest.dateTime) && - Objects.equals(this.uuid, formatTest.uuid) && - Objects.equals(this.password, formatTest.password); - } - - @Override - public int hashCode() { - return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class FormatTest {\n"); - - sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); - sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); - sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); - sb.append(" number: ").append(toIndentedString(number)).append("\n"); - sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); - sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); - sb.append(" string: ").append(toIndentedString(string)).append("\n"); - sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); - sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); - sb.append(" date: ").append(toIndentedString(date)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.Date; +import javax.validation.constraints.*; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private Date date = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") +// @Min(10) +// @Max(100) + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") +// @Min(20) +// @Max(200) + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + @NotNull +// @Min(32.1) +// @Max(543.2) + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") +// @Min(54.3) +// @Max(987.6) + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") +// @Min(67.8) +// @Max(123.4) + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(Date date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public FormatTest dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 73611bc43e0..bcc6487e630 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -1,93 +1,94 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * HasOnlyReadOnly - */ - -public class HasOnlyReadOnly { - @JsonProperty("bar") - private String bar = null; - - @JsonProperty("foo") - private String foo = null; - - /** - * Get bar - * @return bar - **/ - @ApiModelProperty(value = "") - public String getBar() { - return bar; - } - - /** - * Get foo - * @return foo - **/ - @ApiModelProperty(value = "") - public String getFoo() { - return foo; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(this.bar, hasOnlyReadOnly.bar) && - Objects.equals(this.foo, hasOnlyReadOnly.foo); - } - - @Override - public int hashCode() { - return Objects.hash(bar, foo); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class HasOnlyReadOnly {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java index 58037229c3e..9a6b68d03a7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java @@ -1,156 +1,157 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * MapTest - */ - -public class MapTest { - @JsonProperty("map_map_of_string") - private Map> mapMapOfString = new HashMap>(); - - /** - * Gets or Sets inner - */ - public enum InnerEnum { - UPPER("UPPER"), - - LOWER("lower"); - - private String value; - - InnerEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static InnerEnum fromValue(String text) { - for (InnerEnum b : InnerEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("map_of_enum_string") - private Map mapOfEnumString = new HashMap(); - - public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - return this; - } - - public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { - this.mapMapOfString.put(key, mapMapOfStringItem); - return this; - } - - /** - * Get mapMapOfString - * @return mapMapOfString - **/ - @ApiModelProperty(value = "") - public Map> getMapMapOfString() { - return mapMapOfString; - } - - public void setMapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; - } - - public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - return this; - } - - public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { - this.mapOfEnumString.put(key, mapOfEnumStringItem); - return this; - } - - /** - * Get mapOfEnumString - * @return mapOfEnumString - **/ - @ApiModelProperty(value = "") - public Map getMapOfEnumString() { - return mapOfEnumString; - } - - public void setMapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MapTest mapTest = (MapTest) o; - return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); - } - - @Override - public int hashCode() { - return Objects.hash(mapMapOfString, mapOfEnumString); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MapTest {\n"); - - sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); - sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d9c75346f4d..2ee96c79560 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -1,144 +1,145 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Animal; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * MixedPropertiesAndAdditionalPropertiesClass - */ - -public class MixedPropertiesAndAdditionalPropertiesClass { - @JsonProperty("uuid") - private String uuid = null; - - @JsonProperty("dateTime") - private Date dateTime = null; - - @JsonProperty("map") - private Map map = new HashMap(); - - public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { - this.uuid = uuid; - return this; - } - - /** - * Get uuid - * @return uuid - **/ - @ApiModelProperty(value = "") - public String getUuid() { - return uuid; - } - - public void setUuid(String uuid) { - this.uuid = uuid; - } - - public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { - this.dateTime = dateTime; - return this; - } - - /** - * Get dateTime - * @return dateTime - **/ - @ApiModelProperty(value = "") - public Date getDateTime() { - return dateTime; - } - - public void setDateTime(Date dateTime) { - this.dateTime = dateTime; - } - - public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; - return this; - } - - public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { - this.map.put(key, mapItem); - return this; - } - - /** - * Get map - * @return map - **/ - @ApiModelProperty(value = "") - public Map getMap() { - return map; - } - - public void setMap(Map map) { - this.map = map; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); - } - - @Override - public int hashCode() { - return Objects.hash(uuid, dateTime, map); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); - - sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); - sb.append(" map: ").append(toIndentedString(map)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private Date dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(Date dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public Date getDateTime() { + return dateTime; + } + + public void setDateTime(Date dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java index 78c6e9c7e93..f84b190bdac 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java @@ -1,112 +1,113 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing model name starting with number - */ -@ApiModel(description = "Model for testing model name starting with number") - -public class Model200Response { - @JsonProperty("name") - private Integer name = null; - - @JsonProperty("class") - private String propertyClass = null; - - public Model200Response name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public Integer getName() { - return name; - } - - public void setName(Integer name) { - this.name = name; - } - - public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; - return this; - } - - /** - * Get propertyClass - * @return propertyClass - **/ - @ApiModelProperty(value = "") - public String getPropertyClass() { - return propertyClass; - } - - public void setPropertyClass(String propertyClass) { - this.propertyClass = propertyClass; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Model200Response _200Response = (Model200Response) o; - return Objects.equals(this.name, _200Response.name) && - Objects.equals(this.propertyClass, _200Response.propertyClass); - } - - @Override - public int hashCode() { - return Objects.hash(name, propertyClass); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Model200Response {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java index c80ea613b76..8f66f1ae0a0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,134 +1,135 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * ModelApiResponse - */ - -public class ModelApiResponse { - @JsonProperty("code") - private Integer code = null; - - @JsonProperty("type") - private String type = null; - - @JsonProperty("message") - private String message = null; - - public ModelApiResponse code(Integer code) { - this.code = code; - return this; - } - - /** - * Get code - * @return code - **/ - @ApiModelProperty(value = "") - public Integer getCode() { - return code; - } - - public void setCode(Integer code) { - this.code = code; - } - - public ModelApiResponse type(String type) { - this.type = type; - return this; - } - - /** - * Get type - * @return type - **/ - @ApiModelProperty(value = "") - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - - public ModelApiResponse message(String message) { - this.message = message; - return this; - } - - /** - * Get message - * @return message - **/ - @ApiModelProperty(value = "") - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(this.code, _apiResponse.code) && - Objects.equals(this.type, _apiResponse.type) && - Objects.equals(this.message, _apiResponse.message); - } - - @Override - public int hashCode() { - return Objects.hash(code, type, message); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelApiResponse {\n"); - - sb.append(" code: ").append(toIndentedString(code)).append("\n"); - sb.append(" type: ").append(toIndentedString(type)).append("\n"); - sb.append(" message: ").append(toIndentedString(message)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java index 7907a3fd186..aba2654d739 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java @@ -1,89 +1,90 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing reserved words - */ -@ApiModel(description = "Model for testing reserved words") - -public class ModelReturn { - @JsonProperty("return") - private Integer _return = null; - - public ModelReturn _return(Integer _return) { - this._return = _return; - return this; - } - - /** - * Get _return - * @return _return - **/ - @ApiModelProperty(value = "") - public Integer getReturn() { - return _return; - } - - public void setReturn(Integer _return) { - this._return = _return; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ModelReturn _return = (ModelReturn) o; - return Objects.equals(this._return, _return._return); - } - - @Override - public int hashCode() { - return Objects.hash(_return); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ModelReturn {\n"); - - sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java index b9ffac6e40d..b81443ca6eb 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -1,140 +1,142 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * Model for testing model name same as property name - */ -@ApiModel(description = "Model for testing model name same as property name") - -public class Name { - @JsonProperty("name") - private Integer name = null; - - @JsonProperty("snake_case") - private Integer snakeCase = null; - - @JsonProperty("property") - private String property = null; - - @JsonProperty("123Number") - private Integer _123Number = null; - - public Name name(Integer name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(required = true, value = "") - public Integer getName() { - return name; - } - - public void setName(Integer name) { - this.name = name; - } - - /** - * Get snakeCase - * @return snakeCase - **/ - @ApiModelProperty(value = "") - public Integer getSnakeCase() { - return snakeCase; - } - - public Name property(String property) { - this.property = property; - return this; - } - - /** - * Get property - * @return property - **/ - @ApiModelProperty(value = "") - public String getProperty() { - return property; - } - - public void setProperty(String property) { - this.property = property; - } - - /** - * Get _123Number - * @return _123Number - **/ - @ApiModelProperty(value = "") - public Integer get123Number() { - return _123Number; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Name name = (Name) o; - return Objects.equals(this.name, name.name) && - Objects.equals(this.snakeCase, name.snakeCase) && - Objects.equals(this.property, name.property) && - Objects.equals(this._123Number, name._123Number); - } - - @Override - public int hashCode() { - return Objects.hash(name, snakeCase, property, _123Number); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Name {\n"); - - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); - sb.append(" property: ").append(toIndentedString(property)).append("\n"); - sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java index a3333adbce0..31847afc70c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java @@ -1,89 +1,90 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.math.BigDecimal; - -/** - * NumberOnly - */ - -public class NumberOnly { - @JsonProperty("JustNumber") - private BigDecimal justNumber = null; - - public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - return this; - } - - /** - * Get justNumber - * @return justNumber - **/ - @ApiModelProperty(value = "") - public BigDecimal getJustNumber() { - return justNumber; - } - - public void setJustNumber(BigDecimal justNumber) { - this.justNumber = justNumber; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(this.justNumber, numberOnly.justNumber); - } - - @Override - public int hashCode() { - return Objects.hash(justNumber); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class NumberOnly {\n"); - - sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index c37f8f4334c..182f4c8298a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -1,239 +1,239 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import java.util.Date; -import javax.validation.constraints.*; - -/** - * Order - */ - -public class Order { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("petId") - private Long petId = null; - - @JsonProperty("quantity") - private Integer quantity = null; - - @JsonProperty("shipDate") - private Date shipDate = null; - - /** - * Order Status - */ - public enum StatusEnum { - PLACED("placed"), - - APPROVED("approved"), - - DELIVERED("delivered"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String text) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("status") - private StatusEnum status = null; - - @JsonProperty("complete") - private Boolean complete = null; - - public Order id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Order petId(Long petId) { - this.petId = petId; - return this; - } - - /** - * Get petId - * @return petId - **/ - @ApiModelProperty(value = "") - public Long getPetId() { - return petId; - } - - public void setPetId(Long petId) { - this.petId = petId; - } - - public Order quantity(Integer quantity) { - this.quantity = quantity; - return this; - } - - /** - * Get quantity - * @return quantity - **/ - @ApiModelProperty(value = "") - public Integer getQuantity() { - return quantity; - } - - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - public Order shipDate(Date shipDate) { - this.shipDate = shipDate; - return this; - } - - /** - * Get shipDate - * @return shipDate - **/ - @ApiModelProperty(value = "") - public Date getShipDate() { - return shipDate; - } - - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - public Order status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * Order Status - * @return status - **/ - @ApiModelProperty(value = "Order Status") - public StatusEnum getStatus() { - return status; - } - - public void setStatus(StatusEnum status) { - this.status = status; - } - - public Order complete(Boolean complete) { - this.complete = complete; - return this; - } - - /** - * Get complete - * @return complete - **/ - @ApiModelProperty(value = "") - public Boolean getComplete() { - return complete; - } - - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Order order = (Order) o; - return Objects.equals(this.id, order.id) && - Objects.equals(this.petId, order.petId) && - Objects.equals(this.quantity, order.quantity) && - Objects.equals(this.shipDate, order.shipDate) && - Objects.equals(this.status, order.status) && - Objects.equals(this.complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.Date; +import javax.validation.constraints.*; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private Date shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..8adbba83671 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index a12394dabce..df945003380 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -1,254 +1,254 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import io.swagger.model.Category; -import io.swagger.model.Tag; -import java.util.ArrayList; -import java.util.List; -import javax.validation.constraints.*; - -/** - * Pet - */ - -public class Pet { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("category") - private Category category = null; - - @JsonProperty("name") - private String name = null; - - @JsonProperty("photoUrls") - private List photoUrls = new ArrayList(); - - @JsonProperty("tags") - private List tags = new ArrayList(); - - /** - * pet status in the store - */ - public enum StatusEnum { - AVAILABLE("available"), - - PENDING("pending"), - - SOLD("sold"); - - private String value; - - StatusEnum(String value) { - this.value = value; - } - - @Override - @JsonValue - public String toString() { - return String.valueOf(value); - } - - @JsonCreator - public static StatusEnum fromValue(String text) { - for (StatusEnum b : StatusEnum.values()) { - if (String.valueOf(b.value).equals(text)) { - return b; - } - } - return null; - } - } - - @JsonProperty("status") - private StatusEnum status = null; - - public Pet id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Pet category(Category category) { - this.category = category; - return this; - } - - /** - * Get category - * @return category - **/ - @ApiModelProperty(value = "") - public Category getCategory() { - return category; - } - - public void setCategory(Category category) { - this.category = category; - } - - public Pet name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(example = "doggie", required = true, value = "") - @NotNull - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; - return this; - } - - public Pet addPhotoUrlsItem(String photoUrlsItem) { - this.photoUrls.add(photoUrlsItem); - return this; - } - - /** - * Get photoUrls - * @return photoUrls - **/ - @ApiModelProperty(required = true, value = "") - @NotNull - public List getPhotoUrls() { - return photoUrls; - } - - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - public Pet tags(List tags) { - this.tags = tags; - return this; - } - - public Pet addTagsItem(Tag tagsItem) { - this.tags.add(tagsItem); - return this; - } - - /** - * Get tags - * @return tags - **/ - @ApiModelProperty(value = "") - public List getTags() { - return tags; - } - - public void setTags(List tags) { - this.tags = tags; - } - - public Pet status(StatusEnum status) { - this.status = status; - return this; - } - - /** - * pet status in the store - * @return status - **/ - @ApiModelProperty(value = "pet status in the store") - public StatusEnum getStatus() { - return status; - } - - public void setStatus(StatusEnum status) { - this.status = status; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Pet pet = (Pet) o; - return Objects.equals(this.id, pet.id) && - Objects.equals(this.category, pet.category) && - Objects.equals(this.name, pet.name) && - Objects.equals(this.photoUrls, pet.photoUrls) && - Objects.equals(this.tags, pet.tags) && - Objects.equals(this.status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 8ce60288125..d5399b10a4a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -1,102 +1,103 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * ReadOnlyFirst - */ - -public class ReadOnlyFirst { - @JsonProperty("bar") - private String bar = null; - - @JsonProperty("baz") - private String baz = null; - - /** - * Get bar - * @return bar - **/ - @ApiModelProperty(value = "") - public String getBar() { - return bar; - } - - public ReadOnlyFirst baz(String baz) { - this.baz = baz; - return this; - } - - /** - * Get baz - * @return baz - **/ - @ApiModelProperty(value = "") - public String getBaz() { - return baz; - } - - public void setBaz(String baz) { - this.baz = baz; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(this.bar, readOnlyFirst.bar) && - Objects.equals(this.baz, readOnlyFirst.baz); - } - - @Override - public int hashCode() { - return Objects.hash(bar, baz); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ReadOnlyFirst {\n"); - - sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); - sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java index a32ef45986a..80ebc22cbc4 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java @@ -1,88 +1,89 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; - -/** - * SpecialModelName - */ - -public class SpecialModelName { - @JsonProperty("$special[property.name]") - private Long specialPropertyName = null; - - public SpecialModelName specialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - return this; - } - - /** - * Get specialPropertyName - * @return specialPropertyName - **/ - @ApiModelProperty(value = "") - public Long getSpecialPropertyName() { - return specialPropertyName; - } - - public void setSpecialPropertyName(Long specialPropertyName) { - this.specialPropertyName = specialPropertyName; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); - } - - @Override - public int hashCode() { - return Objects.hash(specialPropertyName); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class SpecialModelName {\n"); - - sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index 27bce18c966..1587c557c40 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -1,112 +1,112 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * Tag - */ - -public class Tag { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("name") - private String name = null; - - public Tag id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public Tag name(String name) { - this.name = name; - return this; - } - - /** - * Get name - * @return name - **/ - @ApiModelProperty(value = "") - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Tag tag = (Tag) o; - return Objects.equals(this.id, tag.id) && - Objects.equals(this.name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 700b1165976..c1c6353056c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -1,250 +1,250 @@ -/* - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.model; - -import java.util.Objects; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.annotation.JsonCreator; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; -import javax.validation.constraints.*; - -/** - * User - */ - -public class User { - @JsonProperty("id") - private Long id = null; - - @JsonProperty("username") - private String username = null; - - @JsonProperty("firstName") - private String firstName = null; - - @JsonProperty("lastName") - private String lastName = null; - - @JsonProperty("email") - private String email = null; - - @JsonProperty("password") - private String password = null; - - @JsonProperty("phone") - private String phone = null; - - @JsonProperty("userStatus") - private Integer userStatus = null; - - public User id(Long id) { - this.id = id; - return this; - } - - /** - * Get id - * @return id - **/ - @ApiModelProperty(value = "") - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public User username(String username) { - this.username = username; - return this; - } - - /** - * Get username - * @return username - **/ - @ApiModelProperty(value = "") - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public User firstName(String firstName) { - this.firstName = firstName; - return this; - } - - /** - * Get firstName - * @return firstName - **/ - @ApiModelProperty(value = "") - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public User lastName(String lastName) { - this.lastName = lastName; - return this; - } - - /** - * Get lastName - * @return lastName - **/ - @ApiModelProperty(value = "") - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public User email(String email) { - this.email = email; - return this; - } - - /** - * Get email - * @return email - **/ - @ApiModelProperty(value = "") - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public User password(String password) { - this.password = password; - return this; - } - - /** - * Get password - * @return password - **/ - @ApiModelProperty(value = "") - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public User phone(String phone) { - this.phone = phone; - return this; - } - - /** - * Get phone - * @return phone - **/ - @ApiModelProperty(value = "") - public String getPhone() { - return phone; - } - - public void setPhone(String phone) { - this.phone = phone; - } - - public User userStatus(Integer userStatus) { - this.userStatus = userStatus; - return this; - } - - /** - * User Status - * @return userStatus - **/ - @ApiModelProperty(value = "User Status") - public Integer getUserStatus() { - return userStatus; - } - - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(java.lang.Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return Objects.equals(this.id, user.id) && - Objects.equals(this.username, user.username) && - Objects.equals(this.firstName, user.firstName) && - Objects.equals(this.lastName, user.lastName) && - Objects.equals(this.email, user.email) && - Objects.equals(this.password, user.password) && - Objects.equals(this.phone, user.phone) && - Objects.equals(this.userStatus, user.userStatus); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); - } - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(java.lang.Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} - +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java index d4f8e013671..2cdfed7a93a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/FakeApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.FakeApiService; -import io.swagger.api.impl.FakeApiServiceImpl; - - -public class FakeApiServiceFactory { - private final static FakeApiService service = new FakeApiServiceImpl(); - - public static FakeApiService getFakeApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.FakeApiService; +import io.swagger.api.impl.FakeApiServiceImpl; + + +public class FakeApiServiceFactory { + private final static FakeApiService service = new FakeApiServiceImpl(); + + public static FakeApiService getFakeApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java index 43321e8c0e9..648305ae936 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/PetApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.PetApiService; -import io.swagger.api.impl.PetApiServiceImpl; - - -public class PetApiServiceFactory { - private final static PetApiService service = new PetApiServiceImpl(); - - public static PetApiService getPetApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.PetApiService; +import io.swagger.api.impl.PetApiServiceImpl; + + +public class PetApiServiceFactory { + private final static PetApiService service = new PetApiServiceImpl(); + + public static PetApiService getPetApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java index 254fd0a9a7d..b26a4ad0faf 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/StoreApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.StoreApiService; -import io.swagger.api.impl.StoreApiServiceImpl; - - -public class StoreApiServiceFactory { - private final static StoreApiService service = new StoreApiServiceImpl(); - - public static StoreApiService getStoreApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.StoreApiService; +import io.swagger.api.impl.StoreApiServiceImpl; + + +public class StoreApiServiceFactory { + private final static StoreApiService service = new StoreApiServiceImpl(); + + public static StoreApiService getStoreApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java index 4c50105bb50..13e3d0c190f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/factories/UserApiServiceFactory.java @@ -1,13 +1,13 @@ -package io.swagger.api.factories; - -import io.swagger.api.UserApiService; -import io.swagger.api.impl.UserApiServiceImpl; - - -public class UserApiServiceFactory { - private final static UserApiService service = new UserApiServiceImpl(); - - public static UserApiService getUserApi() { - return service; - } -} +package io.swagger.api.factories; + +import io.swagger.api.UserApiService; +import io.swagger.api.impl.UserApiServiceImpl; + + +public class UserApiServiceFactory { + private final static UserApiService service = new UserApiServiceImpl(); + + public static UserApiService getUserApi() { + return service; + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index fffbd9435b1..98b6ea986c6 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -1,37 +1,37 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class FakeApiServiceImpl extends FakeApiService { - @Override - public Response testClientModel(Client body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 8798db5272d..84b2d2d6b03 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,61 +1,62 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.io.File; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class PetApiServiceImpl extends PetApiService { - @Override - public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByStatus( List status, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByTags( List tags, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePetWithForm(String petId, String name, String status, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class PetApiServiceImpl extends PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 30bb60a33b1..4208855e991 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,41 +1,41 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class StoreApiServiceImpl extends StoreApiService { - @Override - public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getInventory(SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getOrderById(String orderId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class StoreApiServiceImpl extends StoreApiService { + @Override + public Response deleteOrder( @Min(1)String orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index fb84c95879a..6868d0a6105 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,61 +1,61 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; - - -public class UserApiServiceImpl extends UserApiService { - @Override - public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response loginUser( String username, String password, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response logoutUser(SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class UserApiServiceImpl extends UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} From 24f486164aed0960a67a1b7a48206477ab0513ed Mon Sep 17 00:00:00 2001 From: "J. Fiala" Date: Fri, 6 Jan 2017 16:18:14 +0100 Subject: [PATCH 220/269] add test for options #4091 --- .../io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java | 2 ++ .../swagger/codegen/options/JaxRSServerOptionsProvider.java | 6 +++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index 8c6c7149f9b..fdcf69690fa 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -56,6 +56,8 @@ public class JaxRSServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSupportJava6(false); times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JaxRSServerOptionsProvider.USE_BEANVALIDATION)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index 57896db9ca6..d76165e61e7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -2,6 +2,7 @@ package io.swagger.codegen.options; import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaCXFServerCodegen; import io.swagger.codegen.languages.JavaClientCodegen; import java.util.Map; @@ -25,6 +26,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { public static final String JODA_DATE_LIBRARY = "joda"; public static final String IMPL_FOLDER_VALUE = "src/main/java/impl"; public static final String JAXRS_DEFAULT_LIBRARY_VALUE = "jersey1"; + public static final String USE_BEANVALIDATION = "true"; + @Override public boolean isServer() { @@ -60,7 +63,8 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.LIBRARY, JAXRS_DEFAULT_LIBRARY_VALUE) .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") //.put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true"); + .put("hideGenerationTimestamp", "true") + .put(JavaCXFServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); return builder.build(); } From 6b17b92bb610d045f59ed2525804287e3b8ffd97 Mon Sep 17 00:00:00 2001 From: "J. Fiala" Date: Fri, 6 Jan 2017 16:46:59 +0100 Subject: [PATCH 221/269] add check for isInteger (integer/decimal) --- .../JavaJaxRS/beanValidation.mustache | 21 ++++++++++++++----- .../gen/java/io/swagger/model/FormatTest.java | 20 +++++++++--------- .../gen/java/io/swagger/model/FormatTest.java | 20 +++++++++--------- 3 files changed, 36 insertions(+), 25 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache index a4443e0fe5f..eead16d7d98 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache @@ -32,11 +32,22 @@ {{^minItems}} {{#maxItems}} @Size(max={{maxItems}}) - {{/maxItems}} - {{/minItems}} +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} {{#minimum}} -// @Min({{minimum}}) + @Min({{minimum}}) {{/minimum}} {{#maximum}} -// @Max({{maximum}}) -{{/maximum}} \ No newline at end of file + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java index e7a6b6584f7..22907d97675 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -78,8 +78,8 @@ public class FormatTest { * @return integer **/ @ApiModelProperty(value = "") -// @Min(10) -// @Max(100) + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -100,8 +100,8 @@ public class FormatTest { * @return int32 **/ @ApiModelProperty(value = "") -// @Min(20) -// @Max(200) + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -141,8 +141,8 @@ public class FormatTest { **/ @ApiModelProperty(required = true, value = "") @NotNull -// @Min(32.1) -// @Max(543.2) + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -163,8 +163,8 @@ public class FormatTest { * @return _float **/ @ApiModelProperty(value = "") -// @Min(54.3) -// @Max(987.6) + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -185,8 +185,8 @@ public class FormatTest { * @return _double **/ @ApiModelProperty(value = "") -// @Min(67.8) -// @Max(123.4) + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index e7a6b6584f7..22907d97675 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -78,8 +78,8 @@ public class FormatTest { * @return integer **/ @ApiModelProperty(value = "") -// @Min(10) -// @Max(100) + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -100,8 +100,8 @@ public class FormatTest { * @return int32 **/ @ApiModelProperty(value = "") -// @Min(20) -// @Max(200) + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -141,8 +141,8 @@ public class FormatTest { **/ @ApiModelProperty(required = true, value = "") @NotNull -// @Min(32.1) -// @Max(543.2) + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -163,8 +163,8 @@ public class FormatTest { * @return _float **/ @ApiModelProperty(value = "") -// @Min(54.3) -// @Max(987.6) + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -185,8 +185,8 @@ public class FormatTest { * @return _double **/ @ApiModelProperty(value = "") -// @Min(67.8) -// @Max(123.4) + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } From 409e1a504c6b175238f24e009855c0017437052f Mon Sep 17 00:00:00 2001 From: Kevin Locke Date: Sat, 7 Jan 2017 06:56:14 -0700 Subject: [PATCH 222/269] Fix Gson parsing of Joda DateTime without millis (#4473) * Fix Gson parsing of Joda DateTime without millis The DateTimeFormatter returned by ISODateTimeFormat.dateTime() only parses dates with millisecond values, and throws IllegalArgumentException when milliseconds are not present. The date-time construct from RFC 3339 Section 5.6 referenced by the Swagger/OpenAPI spec allows fractional second values to be omitted. This results in valid date-time values being rejected by the generated code. This commit fixes the problem by using .dateOptionalTimeParser() for parsing, which correctly handles date-time values without fractional seconds. A previous version of this commit used .dateTimeParser(), which accepted a time without a date and was considered too liberal. Note that .dateTime() must still be used for printing, which is not supported by .dateTimeParser(). Signed-off-by: Kevin Locke * Fix akka-scala date-time parser with Joda As in the previous commit, which fixed Java generators, ISOISODateTimeFormat.dateOptionalTimeParser() should be used for date-time parsing and ISOISODateTimeFormat.dateTime() for printing. Apply the same change to akka-scala. Signed-off-by: Kevin Locke --- .../resources/Java/libraries/okhttp-gson/JSON.mustache | 7 ++++--- .../resources/Java/libraries/retrofit/ApiClient.mustache | 7 ++++--- .../resources/Java/libraries/retrofit2/ApiClient.mustache | 7 ++++--- .../src/main/resources/akka-scala/apiInvoker.mustache | 4 ++-- .../okhttp-gson/src/main/java/io/swagger/client/JSON.java | 7 ++++--- .../src/main/scala/io/swagger/client/core/ApiInvoker.scala | 4 ++-- .../src/main/java/io/swagger/client/JSON.java | 7 ++++--- .../okhttp-gson/src/main/java/io/swagger/client/JSON.java | 7 ++++--- .../src/main/java/io/swagger/client/ApiClient.java | 7 ++++--- .../src/main/java/io/swagger/client/ApiClient.java | 7 ++++--- 10 files changed, 36 insertions(+), 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 06f26da304b..10a377ebb5a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -172,14 +172,15 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -191,7 +192,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index ffbf93a48b4..6e987c5e14d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -354,14 +354,15 @@ class GsonConverterWrapper implements Converter { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -373,7 +374,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } 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 f9434978704..7d4f106a05a 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 @@ -374,14 +374,15 @@ class GsonCustomConverterFactory extends Converter.Factory */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -393,7 +394,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache index 3b8c6ec5fe3..6267b425ba1 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -85,10 +85,10 @@ object ApiInvoker { case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { case JString(s) => - ISODateTimeFormat.dateTimeParser().parseDateTime(s) + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) }, { case d: DateTime => - JString(ISODateTimeFormat.dateTimeParser().print(d)) + JString(ISODateTimeFormat.dateTime().print(d)) })) } diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 4ff3984453d..43b8be5d60c 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -170,14 +170,15 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -189,7 +190,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala index 18505facbd8..73949422393 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -85,10 +85,10 @@ object ApiInvoker { case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { case JString(s) => - ISODateTimeFormat.dateTimeParser().parseDateTime(s) + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) }, { case d: DateTime => - JString(ISODateTimeFormat.dateTimeParser().print(d)) + JString(ISODateTimeFormat.dateTime().print(d)) })) } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java index a734bec47f1..0445a969c0a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/JSON.java @@ -182,14 +182,15 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -201,7 +202,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 5692584772f..d72b38c9568 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -170,14 +170,15 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -189,7 +190,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } 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 be9eadc33ba..6bd0aac79ab 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 @@ -362,14 +362,15 @@ class GsonCustomConverterFactory extends Converter.Factory */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -381,7 +382,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index cc82b88c425..d3eb060514f 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -362,14 +362,15 @@ class GsonCustomConverterFactory extends Converter.Factory */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -381,7 +382,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } From 1e8c7180c509ba86d9b7f5ef9f9802fffa8c00f0 Mon Sep 17 00:00:00 2001 From: Tomek Cejner Date: Sat, 7 Jan 2017 15:40:07 +0100 Subject: [PATCH 223/269] [swift3] allow POST with both body and query parameters (#4490) * [swift3] allow POST with both body and query parameters * Correctly support non-string and optional query parameters. --- .../src/main/resources/swift3/api.mustache | 27 ++++++-- .../Classes/Swaggers/APIs/FakeAPI.swift | 28 ++++++-- .../Classes/Swaggers/APIs/PetAPI.swift | 55 +++++++++------ .../Classes/Swaggers/APIs/StoreAPI.swift | 36 ++++++---- .../Classes/Swaggers/APIs/UserAPI.swift | 67 ++++++++++++------- .../Classes/Swaggers/APIs/FakeAPI.swift | 36 +++++++--- .../Classes/Swaggers/APIs/PetAPI.swift | 55 +++++++++------ .../Classes/Swaggers/APIs/StoreAPI.swift | 36 ++++++---- .../Classes/Swaggers/APIs/UserAPI.swift | 67 ++++++++++++------- .../Classes/Swaggers/APIs/FakeAPI.swift | 36 +++++++--- .../Classes/Swaggers/APIs/PetAPI.swift | 55 +++++++++------ .../Classes/Swaggers/APIs/StoreAPI.swift | 36 ++++++---- .../Classes/Swaggers/APIs/UserAPI.swift | 67 ++++++++++++------- 13 files changed, 403 insertions(+), 198 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift3/api.mustache b/modules/swagger-codegen/src/main/resources/swift3/api.mustache index 6692a303a37..efb24b85634 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/api.mustache @@ -16,6 +16,15 @@ extension {{projectName}}API { {{#description}} /** {{description}} */{{/description}} open class {{classname}}: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + {{#operation}} {{#allParams}} {{#isEnum}} @@ -108,7 +117,17 @@ open class {{classname}}: APIBase { path = path.replacingOccurrences(of: "{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", with: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .literal, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject] + + let url = NSURLComponents(string: URLString) + {{#hasQueryParams}} + url?.queryItems = mapValuesToQueryItems(values:[ + {{#queryParams}} + "{{paramName}}": {{paramName}}{{#hasMore}}, {{/hasMore}} + {{/queryParams}} + ]) + {{/hasQueryParams}} + {{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:Any?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} @@ -116,12 +135,12 @@ open class {{classname}}: APIBase { ]{{/hasMore}}{{/queryParams}} let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: {{#bodyParam}}(url?.string ?? URLString){{/bodyParam}}{{^bodyParam}}URLString{{/bodyParam}}, parameters: convertedParameters, isBody: {{hasBodyParam}}) } {{/operation}} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index f81a52cb9b8..9f9af014045 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -10,6 +10,15 @@ import Alamofire open class FakeAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** To test \"client\" model @@ -26,6 +35,7 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake + - To test \"client\" model - examples: [{contentType=application/json, example={ "client" : "aeiou" }}] @@ -38,12 +48,15 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -119,9 +132,9 @@ open class FakeAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -182,6 +195,7 @@ open class FakeAPI: APIBase { /** To test enum parameters - GET /fake + - To test enum parameters - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) @@ -203,9 +217,9 @@ open class FakeAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 0588a85ade1..97c5ae379fe 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -10,6 +10,15 @@ import Alamofire open class PetAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Add a new pet to the store @@ -39,12 +48,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -80,12 +92,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -177,9 +189,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -265,9 +277,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -352,12 +364,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -389,12 +401,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -437,9 +452,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -490,9 +505,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 8c30504c5c9..08592cd4ff6 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -10,6 +10,15 @@ import Alamofire open class StoreAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Delete purchase order by ID @@ -40,12 +49,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -80,12 +89,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -148,12 +157,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -212,12 +221,15 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 84ba24276e2..ffd4180c589 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -10,6 +10,15 @@ import Alamofire open class UserAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Create user @@ -36,12 +45,15 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -70,12 +82,15 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -104,12 +119,15 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -142,12 +160,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -218,12 +236,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -264,9 +282,9 @@ open class UserAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -298,12 +316,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -335,12 +353,15 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 407320d315c..facf486b9bc 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -11,6 +11,15 @@ import PromiseKit open class FakeAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** To test \"client\" model @@ -44,6 +53,7 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake + - To test \"client\" model - examples: [{contentType=application/json, example={ "client" : "aeiou" }}] @@ -56,12 +66,15 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -167,9 +180,9 @@ open class FakeAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -220,7 +233,7 @@ open class FakeAPI: APIBase { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } @@ -237,7 +250,7 @@ open class FakeAPI: APIBase { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - returns: Promise */ - open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> Promise { + open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Promise { let deferred = Promise.pending() testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in if let error = error { @@ -252,6 +265,7 @@ open class FakeAPI: APIBase { /** To test enum parameters - GET /fake + - To test enum parameters - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) @@ -262,20 +276,20 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:Any?] = [ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger + "enum_query_integer": enumQueryInteger?.encodeToJSON() ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 48a7379ca26..2c27ed9a2fb 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -11,6 +11,15 @@ import PromiseKit open class PetAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Add a new pet to the store @@ -57,12 +66,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -115,12 +127,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -229,9 +241,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -334,9 +346,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -438,12 +450,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -492,12 +504,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -559,9 +574,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -631,9 +646,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index dac3b79dcbe..b82fed22ebb 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -11,6 +11,15 @@ import PromiseKit open class StoreAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Delete purchase order by ID @@ -58,12 +67,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -114,12 +123,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -199,12 +208,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -280,12 +289,15 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 84557cffcb2..63ec5f9765a 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -11,6 +11,15 @@ import PromiseKit open class UserAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Create user @@ -54,12 +63,15 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -105,12 +117,15 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -156,12 +171,15 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -211,12 +229,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -304,12 +322,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -368,9 +386,9 @@ open class UserAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -418,12 +436,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -473,12 +491,15 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 69dab9ff57b..ecb2f15dec3 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -11,6 +11,15 @@ import RxSwift open class FakeAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** To test \"client\" model @@ -46,6 +55,7 @@ open class FakeAPI: APIBase { /** To test \"client\" model - PATCH /fake + - To test \"client\" model - examples: [{contentType=application/json, example={ "client" : "aeiou" }}] @@ -58,12 +68,15 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -171,9 +184,9 @@ open class FakeAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -224,7 +237,7 @@ open class FakeAPI: APIBase { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: Error?) -> Void)) { testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } @@ -241,7 +254,7 @@ open class FakeAPI: APIBase { - parameter enumQueryDouble: (form) Query parameter enum test (double) (optional) - returns: Observable */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> Observable { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Observable { return Observable.create { observer -> Disposable in testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in if let error = error { @@ -258,6 +271,7 @@ open class FakeAPI: APIBase { /** To test enum parameters - GET /fake + - To test enum parameters - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) @@ -268,20 +282,20 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Double? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let nillableParameters: [String:Any?] = [ "enum_query_string_array": enumQueryStringArray, "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger + "enum_query_integer": enumQueryInteger?.encodeToJSON() ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index e5c3f5e3325..97ffacd3764 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -11,6 +11,15 @@ import RxSwift open class PetAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Add a new pet to the store @@ -59,12 +68,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -119,12 +131,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -235,9 +247,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -342,9 +354,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -448,12 +460,12 @@ open class PetAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -504,12 +516,15 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -573,9 +588,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -647,9 +662,9 @@ open class PetAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 4b27503475b..6111487c20e 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -11,6 +11,15 @@ import RxSwift open class StoreAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Delete purchase order by ID @@ -60,12 +69,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -118,12 +127,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -205,12 +214,12 @@ open class StoreAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -288,12 +297,15 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index a6530489f39..7edeab4d0df 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -11,6 +11,15 @@ import RxSwift open class UserAPI: APIBase { + + public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + /** Create user @@ -56,12 +65,15 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -109,12 +121,15 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -162,12 +177,15 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } /** @@ -219,12 +237,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -314,12 +332,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -380,9 +398,9 @@ open class UserAPI: APIBase { ] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) @@ -432,12 +450,12 @@ open class UserAPI: APIBase { let nillableParameters: [String:Any?] = [:] let parameters = APIHelper.rejectNil(nillableParameters) - + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) } /** @@ -489,12 +507,15 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - + + let url = NSURLComponents(string: URLString) + + let convertedParameters = APIHelper.convertBoolToString(parameters) - + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) } } From 69b1e50a951b6296b468e8cfc33706c979603b77 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 7 Jan 2017 17:08:04 -0800 Subject: [PATCH 224/269] updated version --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 8a4792d1406..43fcd5542d1 100644 --- a/pom.xml +++ b/pom.xml @@ -850,7 +850,7 @@ - 1.0.25 + 1.0.26-SNAPSHOT 2.11.1 2.3.4 1.5.12 From 81b5b78fc2ac27070500667d139870fe63ab0012 Mon Sep 17 00:00:00 2001 From: Sreenidhi Sreesha Date: Sun, 8 Jan 2017 01:58:07 -0800 Subject: [PATCH 225/269] Enable support for vendor extensions in CodegenResponse. (#4517) --- .../src/main/java/io/swagger/codegen/CodegenResponse.java | 4 ++++ .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 1 + 2 files changed, 5 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index fb09f820be5..4f1c9c54c3e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -19,6 +19,7 @@ public class CodegenResponse { public Boolean isFile = Boolean.FALSE; public Object schema; public String jsonSchema; + public Map vendorExtensions; public boolean isWildcard() { return "0".equals(code) || "default".equals(code); @@ -68,6 +69,8 @@ public class CodegenResponse { return false; if (schema != null ? !schema.equals(that.schema) : that.schema != null) return false; + if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) + return false; return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; } @@ -91,6 +94,7 @@ public class CodegenResponse { result = 31 * result + (isFile != null ? isFile.hashCode() : 0); result = 31 * result + (schema != null ? schema.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); + result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); return result; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 3c9c970af2a..012970290a5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2190,6 +2190,7 @@ public class DefaultCodegen { r.schema = response.getSchema(); r.examples = toExamples(response.getExamples()); r.jsonSchema = Json.pretty(response); + r.vendorExtensions = response.getVendorExtensions(); addHeaders(response, r.headers); if (r.schema != null) { From 26ead9b58f48f6a7bf51ee2913bb75a9ac8d8c48 Mon Sep 17 00:00:00 2001 From: Alex Nolasco Date: Mon, 9 Jan 2017 05:22:25 -0500 Subject: [PATCH 226/269] Issue 4416 (Assist escapeReservedWord with custom mappings) (#4480) * Preliminary implementation for issue-4416 * Updated README.md with reserved-words-mappings parameter. --- README.md | 4 ++++ .../java/io/swagger/codegen/cmd/Generate.java | 8 +++++-- .../swagger/codegen/plugin/CodeGenMojo.java | 5 ++++ .../io/swagger/codegen/CodegenConfig.java | 5 +++- .../io/swagger/codegen/DefaultCodegen.java | 5 ++++ .../codegen/config/CodegenConfigurator.java | 23 ++++++++++++++++--- .../config/CodegenConfiguratorUtils.java | 9 ++++++++ .../languages/AbstractCSharpCodegen.java | 7 ++++-- .../languages/AbstractJavaCodegen.java | 5 +++- .../codegen/languages/AbstractPhpCodegen.java | 7 ++++-- .../languages/AbstractScalaCodegen.java | 5 +++- .../AbstractTypeScriptClientCodegen.java | 11 +++++---- .../languages/AkkaScalaClientCodegen.java | 3 +++ .../languages/AndroidClientCodegen.java | 5 +++- .../languages/CsharpDotNet2ClientCodegen.java | 5 +++- .../codegen/languages/DartClientCodegen.java | 5 +++- .../languages/ErlangServerCodegen.java | 7 ++++-- .../codegen/languages/FlashClientCodegen.java | 7 ++++-- .../languages/FlaskConnexionCodegen.java | 9 +++++--- .../codegen/languages/GoClientCodegen.java | 7 +++--- .../codegen/languages/GoServerCodegen.java | 3 +++ .../languages/HaskellServantCodegen.java | 7 ++++-- .../codegen/languages/JMeterCodegen.java | 11 +++++---- .../languages/JavascriptClientCodegen.java | 5 +++- ...JavascriptClosureAngularClientCodegen.java | 5 +++- .../languages/NodeJSServerCodegen.java | 9 +++++--- .../codegen/languages/ObjcClientCodegen.java | 11 ++++++++- .../codegen/languages/PerlClientCodegen.java | 5 +++- .../codegen/languages/PhpClientCodegen.java | 5 +++- .../languages/PythonClientCodegen.java | 5 +++- .../codegen/languages/Qt5CPPGenerator.java | 7 ++++-- .../languages/Rails5ServerCodegen.java | 5 +++- .../codegen/languages/RubyClientCodegen.java | 5 +++- .../codegen/languages/SilexServerCodegen.java | 7 ++++-- .../languages/SinatraServerCodegen.java | 5 +++- .../languages/SlimFrameworkServerCodegen.java | 5 +++- .../codegen/languages/StaticDocCodegen.java | 5 +++- .../codegen/languages/Swift3Codegen.java | 7 ++++-- .../codegen/languages/SwiftCodegen.java | 11 +++++---- .../codegen/languages/TizenClientCodegen.java | 5 +++- .../io/swagger/codegen/utils/OptionUtils.java | 8 +++---- 41 files changed, 214 insertions(+), 64 deletions(-) diff --git a/README.md b/README.md index 3024c333569..1c52130cf48 100644 --- a/README.md +++ b/README.md @@ -289,6 +289,10 @@ OPTIONS the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String + --reserved-words-mappings + specifies how a reserved name should be escaped to. Otherwise, the + default _ is used. For example id=identifier + -v, --verbose verbose mode diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 8c7beab502b..482a630c976 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -117,7 +117,11 @@ public class Generate implements Runnable { @Option(name = {"--http-user-agent"}, title = "http user agent", description = CodegenConstants.HTTP_USER_AGENT_DESC) private String httpUserAgent; - + + @Option(name = {"--reserved-words-mappings"}, title = "import mappings", + description = "specifies how a reserved name should be escaped to. Otherwise, the default _ is used. For example id=identifier") + private String reservedWordsMappings; + @Override public void run() { @@ -217,7 +221,7 @@ public class Generate implements Runnable { applyTypeMappingsKvp(typeMappings, configurator); applyAdditionalPropertiesKvp(additionalProperties, configurator); applyLanguageSpecificPrimitivesCsv(languageSpecificPrimitives, configurator); - + applyReservedWordsMappingsKvp(reservedWordsMappings, configurator); final ClientOptInput clientOptInput = configurator.toClientOptInput(); new DefaultGenerator().opts(clientOptInput).generate(); diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 813762112d2..56472b713d2 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -21,6 +21,7 @@ import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMapp import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp; import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv; import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp; +import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.io.File; @@ -284,6 +285,10 @@ public class CodeGenMojo extends AbstractMojo { if(configOptions.containsKey("additional-properties")) { applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), configurator); } + + if(configOptions.containsKey("reserved-words-mappings")) { + applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings").toString(), configurator); + } } if (environmentVariables != null) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4b0ef89593f..f48d3f090e6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -14,7 +14,7 @@ import com.samskivert.mustache.Mustache.Compiler; public interface CodegenConfig { CodegenType getTag(); - + String getName(); String getHelp(); @@ -118,6 +118,8 @@ public interface CodegenConfig { Map modelDocTemplateFiles(); Set languageSpecificPrimitives(); + + Map reservedWordsMappings(); void preprocessSwagger(Swagger swagger); @@ -197,4 +199,5 @@ public interface CodegenConfig { String getHttpUserAgent(); String getCommonTemplateDir(); + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 012970290a5..f0596ae0ec6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -92,6 +92,7 @@ public class DefaultCodegen { protected Map modelTestTemplateFiles = new HashMap(); protected Map apiDocTemplateFiles = new HashMap(); protected Map modelDocTemplateFiles = new HashMap(); + protected Map reservedWordsMappings = new HashMap(); protected String templateDir; protected String embeddedTemplateDir; protected String commonTemplateDir = "_common"; @@ -468,6 +469,10 @@ public class DefaultCodegen { public Map modelDocTemplateFiles() { return modelDocTemplateFiles; } + + public Map reservedWordsMappings() { + return reservedWordsMappings; + } public Map apiTestTemplateFiles() { return apiTestTemplateFiles; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 6ac586af8f4..7d95e6d18c2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -60,6 +60,8 @@ public class CodegenConfigurator { private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); + private Map reservedWordMappings = new HashMap(); + private String gitUserId="GIT_USER_ID"; private String gitRepoId="GIT_REPO_ID"; private String releaseNote="Minor update"; @@ -263,7 +265,7 @@ public class CodegenConfigurator { this.additionalProperties = additionalProperties; return this; } - + public CodegenConfigurator addAdditionalProperty(String key, Object value) { this.additionalProperties.put(key, value); return this; @@ -341,7 +343,21 @@ public class CodegenConfigurator { this.httpUserAgent= httpUserAgent; return this; } - + + public Map getReservedWordsMappings() { + return reservedWordMappings; + } + + public CodegenConfigurator setReservedWordsMappings(Map reservedWordsMappings) { + this.reservedWordMappings = reservedWordsMappings; + return this; + } + + public CodegenConfigurator addAdditionalReservedWordMapping(String key, String value) { + this.reservedWordMappings.put(key, value); + return this; + } + public ClientOptInput toClientOptInput() { Validate.notEmpty(lang, "language must be specified"); @@ -360,7 +376,8 @@ public class CodegenConfigurator { config.typeMapping().putAll(typeMappings); config.importMapping().putAll(importMappings); config.languageSpecificPrimitives().addAll(languageSpecificPrimitives); - + config.reservedWordsMappings().putAll(reservedWordMappings); + checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE); checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE); checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java index b5a6a6355be..90a96837797 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java @@ -58,6 +58,13 @@ public final class CodegenConfiguratorUtils { } } + public static void applyReservedWordsMappingsKvp(String reservedWordMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(reservedWordMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addAdditionalReservedWordMapping(entry.getKey(), entry.getValue()); + } + } + private static Set createSetFromCsvList(String csvProperty) { final List values = OptionUtils.splitCommaSeparatedList(csvProperty); return new HashSet(values); @@ -74,4 +81,6 @@ public final class CodegenConfiguratorUtils { return result; } + + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 16945708fa2..71c35053988 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -401,10 +401,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } return name; - } + } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 01193f8a0aa..5c22bd82334 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -328,7 +328,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java index c568f6b302f..8d9c3e6c7fc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -251,8 +251,11 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg .replaceAll(regLastPathSeparator+ "$", ""); } - @Override - public String escapeReservedWord(String name) { + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java index e482fa1dd27..cd9a5fd3432 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -67,7 +67,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 96505626911..79adcab1599 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -114,10 +114,13 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp return CodegenType.CLIENT; } - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } @Override public String apiFileFolder() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 8be1c1f6d50..d77763a126d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -154,6 +154,9 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "`" + name + "`"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 4fb1660db46..ba96eb2e6e9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -119,7 +119,10 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index dbcf9d70613..404e01c145b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -170,7 +170,10 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 8d2591f0521..d2a09a8ee3c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -174,7 +174,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java index 65162cdd228..5a78713b414 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -182,8 +182,11 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return name + "_"; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index 2d00c8cf7a2..1a9cbdd6299 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -177,8 +177,11 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { - return name + "_"; + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index e0c7218b723..e99a6b29e38 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -236,10 +236,13 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name } - + /** * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index f6e91d1795e..240dd53a20e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -180,9 +180,10 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { // - XName // - X_Name // ... or maybe a suffix? - // - Name_ ... think this will work. - - // FIXME: This should also really be a customizable option + // - Name_ ... think this will work. + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return camelize(name) + '_'; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index 39c544fba42..b7d2b00967a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -204,6 +204,9 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig { */ @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; // add an underscore to the name } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 526ce0b10b2..97f73fcebb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -154,8 +154,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return name + "_"; + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } public String firstLetterToUpper(String word) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 89893176493..886e6d43d80 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -119,10 +119,13 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { * * @return the escaped term */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } /** * Location to write model files. You can use the modelPackage() as defined when the class is diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 9d661b88d3c..4b345375051 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -313,7 +313,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 0b619824c4d..779f51d178b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -102,7 +102,10 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 87e44d23632..f4fc2a4d8c7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -147,13 +147,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig /** * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * those terms here. This logic is only called if a variable matches the reserved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 3714e7f3834..3da8c5b074b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -538,8 +538,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return toVarName(name); } + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reserved words + * + * @return the escaped term + */ @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index db892f8a7ff..c0d9a0ef2ba 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -161,7 +161,10 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index f054038d134..cf457bbd06c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -307,7 +307,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 47804af0242..38e4a75491c 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -251,7 +251,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 1fffc566855..18ae0170d52 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -198,8 +198,11 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index 5147d4a5b00..dd35131cb74 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -186,7 +186,10 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index a8865196273..4dca4806180 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -330,7 +330,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java index a840b77e05a..9fe6eb2b34a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java @@ -107,10 +107,13 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } - + @Override public String apiFileFolder() { return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index e68d6c3509c..32506898bcf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -104,7 +104,10 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 6eb5beb9e61..042dd6b1bb0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -118,7 +118,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index 4251db48bbb..b2eb5e099b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -77,7 +77,10 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index 1b2e6686ad3..240ceec9a75 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -235,10 +235,13 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; // add an underscore to the name } - + @Override public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index c3430a63700..f72844a0466 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -232,11 +232,14 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { protected boolean isReservedWord(String word) { return word != null && reservedWords.contains(word); //don't lowercase as super does } - + @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name + } @Override public String modelFileFolder() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 3327972665d..5b25ecb44e0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -261,7 +261,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java index 52afb51c89c..27322b4554f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java @@ -1,9 +1,10 @@ package io.swagger.codegen.utils; import org.apache.commons.lang3.tuple.Pair; - import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import joptsimple.internal.Strings; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @@ -22,10 +23,10 @@ public class OptionUtils { results.add(pair); } } - + //Strings.isNullOrEmpty(input) return results; } - + public static List splitCommaSeparatedList(String input) { List results = new ArrayList(); @@ -39,5 +40,4 @@ public class OptionUtils { return results; } - } From 380bed15d30fc536e89f6920447edbc4d7f12e50 Mon Sep 17 00:00:00 2001 From: Jeff Haynes Date: Mon, 9 Jan 2017 04:28:27 -0600 Subject: [PATCH 227/269] Issue 4244 - Add x-discriminator-value (#4252) * Fixes for issue 4226. Detects and warns about more than one inline object; sets discriminator on CodegenModel; Adds templates to other Java languages Changes to be committed: modified: modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java modified: modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache new file: modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache new file: modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache new file: modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache * Add vendor extension for x-discriminator-value Changes to be committed: modified: modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache * Add "visible = true" to @JsonTypeInfo jackson annotations for Java languages Changes to be committed: modified: modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache modified: modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache --- .../io/swagger/codegen/DefaultCodegen.java | 22 +++++++++++++++++-- .../Java/typeInfoAnnotation.mustache | 10 +++++---- .../JavaInflector/typeInfoAnnotation.mustache | 7 ++++++ .../JavaJaxRS/typeInfoAnnotation.mustache | 7 ++++++ .../JavaSpring/typeInfoAnnotation.mustache | 7 ++++++ 5 files changed, 47 insertions(+), 6 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index f0596ae0ec6..09a1329a9da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -186,12 +186,18 @@ public class DefaultCodegen { for (String name : allModels.keySet()) { CodegenModel cm = allModels.get(name); CodegenModel parent = allModels.get(cm.parent); + // if a discriminator exists on the parent, don't add this child to the inheritance heirarchy + // TODO Determine what to do if the parent discriminator name == the grandparent discriminator name while (parent != null) { if (parent.children == null) { - parent.children = new ArrayList(); + parent.children = new ArrayList(); } parent.children.add(cm); - parent = allModels.get(parent.parent); + if (parent.discriminator == null) { + parent = allModels.get(parent.parent); + } else { + parent = null; + } } } } @@ -1270,6 +1276,18 @@ public class DefaultCodegen { allProperties = new LinkedHashMap(); allRequired = new ArrayList(); m.allVars = new ArrayList(); + int modelImplCnt = 0; // only one inline object allowed in a ComposedModel + for (Model innerModel: ((ComposedModel)model).getAllOf()) { + if (innerModel instanceof ModelImpl) { + if (m.discriminator == null) { + m.discriminator = ((ModelImpl) innerModel).getDiscriminator(); + } + if (modelImplCnt++ > 1) { + LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); + break; // only one ModelImpl with discriminator allowed in allOf + } + } + } } else { allProperties = null; allRequired = null; diff --git a/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache index 6ef9431ff60..b3083e788d9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache @@ -1,5 +1,7 @@ {{#jackson}} -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}" ) -@JsonSubTypes({ - {{#children}}@JsonSubTypes.Type(value = {{name}}.class, name = "{{name}}"),{{/children}} -}){{/jackson}} \ No newline at end of file +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} From 4d4af7144656c80e8e63779191fd5a22fce65dc8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 9 Jan 2017 18:29:41 +0800 Subject: [PATCH 228/269] [CI] Add scripts to detect carriage return and tab (#4526) * add script to detect carriage return * add check for generator as well * add fail fast to travis config * remove tab * move scripts under bin/utils * remove carriage return * move scripts to bin/utils --- .travis.yml | 8 + bin/utils/detect_carriage_return.sh | 18 + bin/utils/detect_tab_in_java_class.sh | 10 + .../main/java/io/swagger/codegen/Codegen.java | 4 +- .../src/main/resources/Java/api_test.mustache | 90 ++-- .../Java/libraries/okhttp-gson/api.mustache | 442 +++++++++--------- .../main/resources/JavaJaxRS/cxf/api.mustache | 88 ++-- .../server/swagger-codegen-ignore.mustache | 48 +- 8 files changed, 372 insertions(+), 336 deletions(-) create mode 100755 bin/utils/detect_carriage_return.sh create mode 100755 bin/utils/detect_tab_in_java_class.sh diff --git a/.travis.yml b/.travis.yml index 1a62cea3161..68a526cf1b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -34,7 +34,15 @@ install: - export PATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH" script: + # fail fast + - set -e + # fail if templates/generators contain carriage return '\r' + - /bin/bash ./bin/utils/detect_carriage_return.sh + # fail if generators contain tab '\t' + - /bin/bash ./bin/utils/detect_tab_in_java_class.sh + # run integration tests defined in maven pom.xml - mvn verify -Psamples + # docker test - if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: diff --git a/bin/utils/detect_carriage_return.sh b/bin/utils/detect_carriage_return.sh new file mode 100755 index 00000000000..e55c64f64b6 --- /dev/null +++ b/bin/utils/detect_carriage_return.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# grep for \r in the templates +grep -RUIl $'\r$' modules/swagger-codegen/src/main/resources/* + +if [ $? -ne 1 ]; then + echo "Templates contain carriage return '/r'. Please remove it and try again." + exit 1; +fi + + +# grep for \r in the generators +grep -RUIl $'\r$' modules/swagger-codegen/src/main/java/io/swagger/codegen/*.java + +if [ $? -ne 1 ]; then + echo "Generators contain carriage return '/r'. Please remove it and try again." + exit 1; +fi diff --git a/bin/utils/detect_tab_in_java_class.sh b/bin/utils/detect_tab_in_java_class.sh new file mode 100755 index 00000000000..8d612acd2e0 --- /dev/null +++ b/bin/utils/detect_tab_in_java_class.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# grep for \t in the generators +grep -RUIl $'\t$' modules/swagger-codegen/src/main/java/io/swagger/codegen/*.java + +if [ $? -ne 1 ]; then + echo "Generators (Java class files) contain tab '/t'. Please remove it and try again." + exit 1; +fi + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index c4f0dc1ce7a..839f0800e15 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -25,9 +25,9 @@ import io.swagger.parser.SwaggerParser; */ @Deprecated public class Codegen extends DefaultGenerator { - + private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class); - + static Map configs = new HashMap(); static String configString; static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache index 4ff7c577ac0..1d95ac2ed89 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache @@ -1,45 +1,45 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiException; -{{#imports}}import {{import}}; -{{/imports}} -import org.junit.Test; -import org.junit.Ignore; - -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -/** - * API tests for {{classname}} - */ -@Ignore -public class {{classname}}Test { - - private final {{classname}} api = new {{classname}}(); - - {{#operations}}{{#operation}} - /** - * {{summary}} - * - * {{notes}} - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void {{operationId}}Test() throws ApiException { - {{#allParams}} - {{{dataType}}} {{paramName}} = null; - {{/allParams}} - {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - // TODO: test validations - } - {{/operation}}{{/operations}} -} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +@Ignore +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index 04c3918f260..0cd19c24efa 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -1,221 +1,221 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiCallback; -import {{invokerPackage}}.ApiClient; -import {{invokerPackage}}.ApiException; -import {{invokerPackage}}.ApiResponse; -import {{invokerPackage}}.Configuration; -import {{invokerPackage}}.Pair; -import {{invokerPackage}}.ProgressRequestBody; -import {{invokerPackage}}.ProgressResponseBody; -{{#performBeanValidation}} -import {{invokerPackage}}.BeanValidationException; -{{/performBeanValidation}} - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{#performBeanValidation}} -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.executable.ExecutableValidator; -import java.util.Set; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -{{/performBeanValidation}} - -{{#imports}}import {{import}}; -{{/imports}} - -import java.lang.reflect.Type; -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -{{#operations}} -public class {{classname}} { - private ApiClient {{localVariablePrefix}}apiClient; - - public {{classname}}() { - this(Configuration.getDefaultApiClient()); - } - - public {{classname}}(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - public ApiClient getApiClient() { - return {{localVariablePrefix}}apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - {{#operation}} - /* Build call for {{operationId}} */ - private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - - // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} - - final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); - if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); - - final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); - {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - {{^performBeanValidation}} - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); - } - {{/required}}{{/allParams}} - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - {{/performBeanValidation}} - {{#performBeanValidation}} - try { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - ExecutableValidator executableValidator = factory.getValidator().forExecutables(); - - Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; - Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); - Set> violations = executableValidator.validateParameters(this, method, - parameterValues); - - if (violations.size() == 0) { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - } else { - throw new BeanValidationException((Set) violations); - } - } catch (NoSuchMethodException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } catch (SecurityException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } - - {{/performBeanValidation}} - - - - - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{returnType}}{{/returnType}} - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} - return {{localVariablePrefix}}resp.getData();{{/returnType}} - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} - } - - /** - * {{summary}} (asynchronously) - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} - return {{localVariablePrefix}}call; - } - {{/operation}} -} -{{/operations}} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiResponse; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ProgressRequestBody; +import {{invokerPackage}}.ProgressResponseBody; +{{#performBeanValidation}} +import {{invokerPackage}}.BeanValidationException; +{{/performBeanValidation}} + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{#performBeanValidation}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; +import java.util.Set; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +{{/performBeanValidation}} + +{{#imports}}import {{import}}; +{{/imports}} + +import java.lang.reflect.Type; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{operationId}} */ + private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + + // create path and map variables + String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); + if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); + + final String[] {{localVariablePrefix}}localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); + {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + {{^performBeanValidation}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + {{/performBeanValidation}} + {{#performBeanValidation}} + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ExecutableValidator executableValidator = factory.getValidator().forExecutables(); + + Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; + Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); + Set> violations = executableValidator.validateParameters(this, method, + parameterValues); + + if (violations.size() == 0) { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + } else { + throw new BeanValidationException((Set) violations); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } catch (SecurityException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } + + {{/performBeanValidation}} + + + + + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 47062c394d2..d54737c415c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -1,44 +1,44 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} - -@Path("/") -@Api(value = "/", description = "{{description}}") -{{#addConsumesProducesJson}} -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) -{{/addConsumesProducesJson}} -public interface {{classname}} { -{{#operations}} -{{#operation}} - - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} -{{#hasConsumes}} - @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) -{{/hasConsumes}} -{{#hasProduces}} - @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) -{{/hasProduces}} - @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) - public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); -{{/operation}} -} -{{/operations}} - +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} + +@Path("/") +@Api(value = "/", description = "{{description}}") +{{#addConsumesProducesJson}} +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +{{/addConsumesProducesJson}} +public interface {{classname}} { +{{#operations}} +{{#operation}} + + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} +{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) +{{/hasConsumes}} +{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) +{{/hasProduces}} + @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache index ec46bbd69c0..70b88e71039 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache @@ -1,25 +1,25 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# Use this file to prevent files from being overwritten by the generator. -# The patterns follow closely to .gitignore or .dockerignore. - -# As an example, the C# client generator defines ApiClient.cs. -# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: -#ApiClient.cs - -# You can match any string of characters against a directory, file or extension with a single asterisk (*): -#foo/*/qux -# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux - -# You can recursively match patterns against a directory, file or extension with a double asterisk (**): -#foo/**/qux -# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux - -# You can also negate patterns with an exclamation (!). -# For example, you can ignore all files in a docs folder with the file extension .md: -#docs/*.md -# Then explicitly reverse the ignore rule for a single file: -#!docs/README.md - +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md + **/impl/* \ No newline at end of file From de5ea8a9d63430a7f3ec8013760a74018b5a9b51 Mon Sep 17 00:00:00 2001 From: Yuta HIGUCHI Date: Tue, 10 Jan 2017 07:37:25 -0800 Subject: [PATCH 229/269] [JAX-RS/jersey2] Fix for incorrect JSON field name capitalization (#4458) * Fix for all capital field name * Cosmetic: remove trailing spaces * Adding ./bin/jaxrs-petstore-server.sh output. --- .../main/resources/JavaJaxRS/pojo.mustache | 3 + ...ith-fake-endpoints-models-for-testing.yaml | 53 +++-- samples/server/petstore/jaxrs/jersey2/pom.xml | 9 + .../src/gen/java/io/swagger/api/FakeApi.java | 6 +- .../java/io/swagger/api/FakeApiService.java | 2 +- .../model/AdditionalPropertiesClass.java | 2 + .../src/gen/java/io/swagger/model/Animal.java | 4 + .../model/ArrayOfArrayOfNumberOnly.java | 1 + .../io/swagger/model/ArrayOfNumberOnly.java | 1 + .../gen/java/io/swagger/model/ArrayTest.java | 3 + .../java/io/swagger/model/Capitalization.java | 209 ++++++++++++++++++ .../src/gen/java/io/swagger/model/Cat.java | 1 + .../gen/java/io/swagger/model/Category.java | 2 + .../gen/java/io/swagger/model/ClassModel.java | 90 ++++++++ .../src/gen/java/io/swagger/model/Client.java | 1 + .../src/gen/java/io/swagger/model/Dog.java | 1 + .../gen/java/io/swagger/model/EnumArrays.java | 2 + .../gen/java/io/swagger/model/EnumTest.java | 32 ++- .../gen/java/io/swagger/model/FormatTest.java | 21 +- .../io/swagger/model/HasOnlyReadOnly.java | 2 + .../gen/java/io/swagger/model/MapTest.java | 2 + ...ropertiesAndAdditionalPropertiesClass.java | 3 + .../io/swagger/model/Model200Response.java | 2 + .../io/swagger/model/ModelApiResponse.java | 3 + .../java/io/swagger/model/ModelReturn.java | 1 + .../src/gen/java/io/swagger/model/Name.java | 4 + .../gen/java/io/swagger/model/NumberOnly.java | 1 + .../src/gen/java/io/swagger/model/Order.java | 6 + .../gen/java/io/swagger/model/OuterEnum.java | 53 +++++ .../src/gen/java/io/swagger/model/Pet.java | 6 + .../java/io/swagger/model/ReadOnlyFirst.java | 2 + .../io/swagger/model/SpecialModelName.java | 1 + .../src/gen/java/io/swagger/model/Tag.java | 2 + .../src/gen/java/io/swagger/model/User.java | 8 + .../swagger/api/impl/FakeApiServiceImpl.java | 2 +- .../io/swagger/model/CapitalizationTest.java | 69 ++++++ 36 files changed, 581 insertions(+), 29 deletions(-) create mode 100644 samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java create mode 100644 samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index f3a36ecc387..489dd2ac82f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -66,6 +66,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{#vendorExtensions.extraAnnotation}} {{vendorExtensions.extraAnnotation}} {{/vendorExtensions.extraAnnotation}} + {{#jackson}} + @JsonProperty("{{baseName}}") + {{/jackson}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 0303e6bbec6..552dd2ee0ee 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1,16 +1,16 @@ swagger: '2.0' info: description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" - version: 1.0.0 - title: Swagger Petstore + version: 1.0.0 + title: Swagger Petstore termsOfService: 'http://swagger.io/terms/' contact: - email: apiteam@swagger.io + email: apiteam@swagger.io license: - name: Apache 2.0 + name: Apache 2.0 url: 'http://www.apache.org/licenses/LICENSE-2.0.html' -host: petstore.swagger.io -basePath: /v2 +host: petstore.swagger.io +basePath: /v2 tags: - name: pet description: Everything about your Pets @@ -611,7 +611,7 @@ paths: - _abc - '-efg' - (xyz) - in: formData + in: formData description: Form parameter enum test (string) - name: enum_header_string_array type: array @@ -621,7 +621,7 @@ paths: enum: - '>' - '$' - in: header + in: header description: Header parameter enum test (string array) - name: enum_header_string type: string @@ -633,7 +633,7 @@ paths: in: header description: Header parameter enum test (string) - name: enum_query_string_array - type: array + type: array items: type: string default: '$' @@ -649,11 +649,11 @@ paths: - _abc - '-efg' - (xyz) - in: query + in: query description: Query parameter enum test (string) - name: enum_query_integer type: integer - format: int32 + format: int32 enum: - 1 - -2 @@ -661,7 +661,7 @@ paths: description: Query parameter enum test (double) - name: enum_query_double type: number - format: double + format: double enum: - 1.1 - -1.2 @@ -674,7 +674,7 @@ paths: description: Not found post: tags: - - fake + - fake summary: | Fake endpoint for testing various parameters 假端點 @@ -1046,7 +1046,7 @@ definitions: format: date-time uuid: type: string - format: uuid + format: uuid password: type: string format: password @@ -1104,7 +1104,7 @@ definitions: dateTime: type: string format: date-time - map: + map: type: object additionalProperties: $ref: '#/definitions/Animal' @@ -1135,6 +1135,23 @@ definitions: foo: type: string readOnly: true + Capitalization: + type: object + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: > + Name of the pet + type: string MapTest: type: object properties: @@ -1143,14 +1160,14 @@ definitions: additionalProperties: type: object additionalProperties: - type: string + type: string # comment out the following (map of map of enum) as many language not yet support this #map_map_of_enum: # type: object # additionalProperties: # type: object # additionalProperties: - # type: string + # type: string # enum: # - UPPER # - lower @@ -1218,7 +1235,7 @@ definitions: type: string enum: - ">=" - - "$" + - "$" array_enum: type: array items: diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index 5f3f512a42d..adcc4323578 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -5,6 +5,15 @@ jar swagger-jaxrs-server 1.0.0 + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + src/main/java diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java index a1e2db5e58a..d094b74b48b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java @@ -36,7 +36,7 @@ public class FakeApi { @Consumes({ "application/json" }) @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) public Response testClientModel(@ApiParam(value = "client model" ,required=true) Client body @@ -77,7 +77,7 @@ public class FakeApi { @Consumes({ "*/*" }) @Produces({ "*/*" }) - @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), @@ -88,7 +88,7 @@ public class FakeApi { ,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString ,@ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray ,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString -,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger +,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") Integer enumQueryInteger ,@ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble ,@Context SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java index 0109f9edc57..de853e00a8f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java @@ -21,5 +21,5 @@ import javax.ws.rs.core.SecurityContext; public abstract class FakeApiService { public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 55d1d0c5e45..488c68d6617 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -47,6 +47,7 @@ public class AdditionalPropertiesClass { * Get mapProperty * @return mapProperty **/ + @JsonProperty("map_property") @ApiModelProperty(value = "") public Map getMapProperty() { return mapProperty; @@ -70,6 +71,7 @@ public class AdditionalPropertiesClass { * Get mapOfMapProperty * @return mapOfMapProperty **/ + @JsonProperty("map_of_map_property") @ApiModelProperty(value = "") public Map> getMapOfMapProperty() { return mapOfMapProperty; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java index ae2b64e8c67..6e16d257cd0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -16,6 +16,8 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @@ -39,6 +41,7 @@ public class Animal { * Get className * @return className **/ + @JsonProperty("className") @ApiModelProperty(required = true, value = "") public String getClassName() { return className; @@ -57,6 +60,7 @@ public class Animal { * Get color * @return color **/ + @JsonProperty("color") @ApiModelProperty(value = "") public String getColor() { return color; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 31be0acd0bd..95d5927e589 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -44,6 +44,7 @@ public class ArrayOfArrayOfNumberOnly { * Get arrayArrayNumber * @return arrayArrayNumber **/ + @JsonProperty("ArrayArrayNumber") @ApiModelProperty(value = "") public List> getArrayArrayNumber() { return arrayArrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 1923213cce9..0e8e84db202 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -44,6 +44,7 @@ public class ArrayOfNumberOnly { * Get arrayNumber * @return arrayNumber **/ + @JsonProperty("ArrayNumber") @ApiModelProperty(value = "") public List getArrayNumber() { return arrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java index ff6ed5937a5..c0ad8c51d97 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java @@ -50,6 +50,7 @@ public class ArrayTest { * Get arrayOfString * @return arrayOfString **/ + @JsonProperty("array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { return arrayOfString; @@ -73,6 +74,7 @@ public class ArrayTest { * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ + @JsonProperty("array_array_of_integer") @ApiModelProperty(value = "") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; @@ -96,6 +98,7 @@ public class ArrayTest { * Get arrayArrayOfModel * @return arrayArrayOfModel **/ + @JsonProperty("array_array_of_model") @ApiModelProperty(value = "") public List> getArrayArrayOfModel() { return arrayArrayOfModel; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..21c51dc433d --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,209 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @JsonProperty("smallCamel") + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @JsonProperty("CapitalCamel") + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @JsonProperty("small_Snake") + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @JsonProperty("Capital_Snake") + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @JsonProperty("SCA_ETH_Flow_Points") + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @JsonProperty("ATT_NAME") + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java index 7fbae697738..b5e8c809e0d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java @@ -37,6 +37,7 @@ public class Cat extends Animal { * Get declawed * @return declawed **/ + @JsonProperty("declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { return declawed; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index 62a809814b5..b0ebd3851e0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -39,6 +39,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +58,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..6ccf3a671f9 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,90 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @JsonProperty("_class") + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java index ad56b48eeb9..fedb5ed327c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java @@ -36,6 +36,7 @@ public class Client { * Get client * @return client **/ + @JsonProperty("client") @ApiModelProperty(value = "") public String getClient() { return client; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java index ca6dc1c3af7..48fe697d32c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java @@ -37,6 +37,7 @@ public class Dog extends Animal { * Get breed * @return breed **/ + @JsonProperty("breed") @ApiModelProperty(value = "") public String getBreed() { return breed; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java index 55feec29353..05693e67530 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java @@ -104,6 +104,7 @@ public class EnumArrays { * Get justSymbol * @return justSymbol **/ + @JsonProperty("just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { return justSymbol; @@ -127,6 +128,7 @@ public class EnumArrays { * Get arrayEnum * @return arrayEnum **/ + @JsonProperty("array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { return arrayEnum; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java index b68b0d79f3b..c95bbb2eb69 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; /** * EnumTest @@ -129,6 +130,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -138,6 +142,7 @@ public class EnumTest { * Get enumString * @return enumString **/ + @JsonProperty("enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { return enumString; @@ -156,6 +161,7 @@ public class EnumTest { * Get enumInteger * @return enumInteger **/ + @JsonProperty("enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { return enumInteger; @@ -174,6 +180,7 @@ public class EnumTest { * Get enumNumber * @return enumNumber **/ + @JsonProperty("enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { return enumNumber; @@ -183,6 +190,25 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @JsonProperty("outerEnum") + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -195,12 +221,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -212,6 +239,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index 203c4a105d8..b68ea803ad3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -72,10 +72,11 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ + @JsonProperty("integer") @ApiModelProperty(value = "") public Integer getInteger() { return integer; @@ -92,10 +93,11 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ + @JsonProperty("int32") @ApiModelProperty(value = "") public Integer getInt32() { return int32; @@ -114,6 +116,7 @@ public class FormatTest { * Get int64 * @return int64 **/ + @JsonProperty("int64") @ApiModelProperty(value = "") public Long getInt64() { return int64; @@ -134,6 +137,7 @@ public class FormatTest { * maximum: 543.2 * @return number **/ + @JsonProperty("number") @ApiModelProperty(required = true, value = "") public BigDecimal getNumber() { return number; @@ -154,6 +158,7 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ + @JsonProperty("float") @ApiModelProperty(value = "") public Float getFloat() { return _float; @@ -174,6 +179,7 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ + @JsonProperty("double") @ApiModelProperty(value = "") public Double getDouble() { return _double; @@ -192,6 +198,7 @@ public class FormatTest { * Get string * @return string **/ + @JsonProperty("string") @ApiModelProperty(value = "") public String getString() { return string; @@ -210,6 +217,7 @@ public class FormatTest { * Get _byte * @return _byte **/ + @JsonProperty("byte") @ApiModelProperty(required = true, value = "") public byte[] getByte() { return _byte; @@ -228,6 +236,7 @@ public class FormatTest { * Get binary * @return binary **/ + @JsonProperty("binary") @ApiModelProperty(value = "") public byte[] getBinary() { return binary; @@ -246,6 +255,7 @@ public class FormatTest { * Get date * @return date **/ + @JsonProperty("date") @ApiModelProperty(required = true, value = "") public Date getDate() { return date; @@ -264,6 +274,7 @@ public class FormatTest { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -282,6 +293,7 @@ public class FormatTest { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") public String getUuid() { return uuid; @@ -300,6 +312,7 @@ public class FormatTest { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(required = true, value = "") public String getPassword() { return password; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 73611bc43e0..c5229bd60d5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -34,6 +34,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -43,6 +44,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ + @JsonProperty("foo") @ApiModelProperty(value = "") public String getFoo() { return foo; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java index 58037229c3e..21fe8ac5050 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java @@ -79,6 +79,7 @@ public class MapTest { * Get mapMapOfString * @return mapMapOfString **/ + @JsonProperty("map_map_of_string") @ApiModelProperty(value = "") public Map> getMapMapOfString() { return mapMapOfString; @@ -102,6 +103,7 @@ public class MapTest { * Get mapOfEnumString * @return mapOfEnumString **/ + @JsonProperty("map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { return mapOfEnumString; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d9c75346f4d..2b9c780a909 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -47,6 +47,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") public String getUuid() { return uuid; @@ -65,6 +66,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -88,6 +90,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get map * @return map **/ + @JsonProperty("map") @ApiModelProperty(value = "") public Map getMap() { return map; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java index 78c6e9c7e93..4ad863ff09b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java @@ -40,6 +40,7 @@ public class Model200Response { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public Integer getName() { return name; @@ -58,6 +59,7 @@ public class Model200Response { * Get propertyClass * @return propertyClass **/ + @JsonProperty("class") @ApiModelProperty(value = "") public String getPropertyClass() { return propertyClass; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java index c80ea613b76..7628999454d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -42,6 +42,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") @ApiModelProperty(value = "") public Integer getCode() { return code; @@ -60,6 +61,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") @ApiModelProperty(value = "") public String getType() { return type; @@ -78,6 +80,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") @ApiModelProperty(value = "") public String getMessage() { return message; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java index 7907a3fd186..61c85bfc20f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java @@ -37,6 +37,7 @@ public class ModelReturn { * Get _return * @return _return **/ + @JsonProperty("return") @ApiModelProperty(value = "") public Integer getReturn() { return _return; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java index b9ffac6e40d..6bdd8121b8b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -46,6 +46,7 @@ public class Name { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(required = true, value = "") public Integer getName() { return name; @@ -59,6 +60,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ + @JsonProperty("snake_case") @ApiModelProperty(value = "") public Integer getSnakeCase() { return snakeCase; @@ -73,6 +75,7 @@ public class Name { * Get property * @return property **/ + @JsonProperty("property") @ApiModelProperty(value = "") public String getProperty() { return property; @@ -86,6 +89,7 @@ public class Name { * Get _123Number * @return _123Number **/ + @JsonProperty("123Number") @ApiModelProperty(value = "") public Integer get123Number() { return _123Number; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java index a3333adbce0..ed21e2a6819 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java @@ -37,6 +37,7 @@ public class NumberOnly { * Get justNumber * @return justNumber **/ + @JsonProperty("JustNumber") @ApiModelProperty(value = "") public BigDecimal getJustNumber() { return justNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index 11e8c7fd70c..e9b79ad89b2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -86,6 +86,7 @@ public class Order { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -104,6 +105,7 @@ public class Order { * Get petId * @return petId **/ + @JsonProperty("petId") @ApiModelProperty(value = "") public Long getPetId() { return petId; @@ -122,6 +124,7 @@ public class Order { * Get quantity * @return quantity **/ + @JsonProperty("quantity") @ApiModelProperty(value = "") public Integer getQuantity() { return quantity; @@ -140,6 +143,7 @@ public class Order { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") @ApiModelProperty(value = "") public Date getShipDate() { return shipDate; @@ -158,6 +162,7 @@ public class Order { * Order Status * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; @@ -176,6 +181,7 @@ public class Order { * Get complete * @return complete **/ + @JsonProperty("complete") @ApiModelProperty(value = "") public Boolean getComplete() { return complete; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..a5242537bba --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,53 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index e7e94cc89a8..8971bd9739b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -89,6 +89,7 @@ public class Pet { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -107,6 +108,7 @@ public class Pet { * Get category * @return category **/ + @JsonProperty("category") @ApiModelProperty(value = "") public Category getCategory() { return category; @@ -125,6 +127,7 @@ public class Pet { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(example = "doggie", required = true, value = "") public String getName() { return name; @@ -148,6 +151,7 @@ public class Pet { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @ApiModelProperty(required = true, value = "") public List getPhotoUrls() { return photoUrls; @@ -171,6 +175,7 @@ public class Pet { * Get tags * @return tags **/ + @JsonProperty("tags") @ApiModelProperty(value = "") public List getTags() { return tags; @@ -189,6 +194,7 @@ public class Pet { * pet status in the store * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 8ce60288125..4c58bf38d79 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -34,6 +34,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -48,6 +49,7 @@ public class ReadOnlyFirst { * Get baz * @return baz **/ + @JsonProperty("baz") @ApiModelProperty(value = "") public String getBaz() { return baz; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java index a32ef45986a..e309bf3d2bd 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java @@ -36,6 +36,7 @@ public class SpecialModelName { * Get specialPropertyName * @return specialPropertyName **/ + @JsonProperty("$special[property.name]") @ApiModelProperty(value = "") public Long getSpecialPropertyName() { return specialPropertyName; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index 4d1d23d8b92..80031e565b9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -39,6 +39,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +58,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 779377d4578..786563d9a51 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -57,6 +57,7 @@ public class User { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -75,6 +76,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") @ApiModelProperty(value = "") public String getUsername() { return username; @@ -93,6 +95,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") @ApiModelProperty(value = "") public String getFirstName() { return firstName; @@ -111,6 +114,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") @ApiModelProperty(value = "") public String getLastName() { return lastName; @@ -129,6 +133,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") @ApiModelProperty(value = "") public String getEmail() { return email; @@ -147,6 +152,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(value = "") public String getPassword() { return password; @@ -165,6 +171,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") @ApiModelProperty(value = "") public String getPhone() { return phone; @@ -183,6 +190,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { return userStatus; diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index fffbd9435b1..7127faf3879 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -30,7 +30,7 @@ public class FakeApiServiceImpl extends FakeApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java b/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java new file mode 100644 index 00000000000..179b064248f --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java @@ -0,0 +1,69 @@ +package io.swagger.model; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Tests JSON representation of + */ +public class CapitalizationTest { + + private static final String SMALL_CAMEL = "smallCamel"; + private static final String SMALL_SNAKE = "small_Snake"; + private static final String CAPITAL_CAMEL = "CapitalCamel"; + private static final String CAPITAL_SNAKE = "Capital_Snake"; + + private static final String SCA_ETH_FLOW_POINTS = "SCA_ETH_Flow_Points"; + private static final String ATT_NAME = "ATT_NAME"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final Set EXPECTED + = new HashSet<>(Arrays.asList(SMALL_CAMEL, + SMALL_SNAKE, + CAPITAL_CAMEL, + CAPITAL_SNAKE, + SCA_ETH_FLOW_POINTS, + ATT_NAME)); + + private Capitalization sut; + + + @Before + public void setUp() { + sut = new Capitalization(); + sut.smallCamel(SMALL_CAMEL); + sut.smallSnake(SMALL_SNAKE); + sut.capitalCamel(CAPITAL_CAMEL); + sut.capitalSnake(CAPITAL_SNAKE); + sut.setScAETHFlowPoints(SCA_ETH_FLOW_POINTS); + sut.setATTNAME(ATT_NAME); + } + + @Test + public void test() throws JsonProcessingException { + + JsonNode json = MAPPER.valueToTree(sut); + + Set fields = new HashSet<>(); + Iterator it = json.fieldNames(); + while (it.hasNext()) { + fields.add(it.next()); + } + + assertThat(fields, is(equalTo(EXPECTED))); + } + +} From c1f854f7da78859d0ec9a54abd4f4381c4bd0a60 Mon Sep 17 00:00:00 2001 From: Krisztian Lachata Date: Tue, 10 Jan 2017 16:27:48 +0000 Subject: [PATCH 230/269] Overriden objectmapper wasn't used in deserialisation (Scala) issue #4532 (#4534) * Overriden objectmapper wasn't used in deserialisation Use previously provided apiInvoker instead of creating a instance at deserialision stage * update scala sample --- .../swagger-codegen/src/main/resources/scala/api.mustache | 2 +- .../src/main/scala/io/swagger/client/api/PetApi.scala | 8 ++++---- .../src/main/scala/io/swagger/client/api/StoreApi.scala | 6 +++--- .../src/main/scala/io/swagger/client/api/UserApi.scala | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 977f4e2b056..177fc96cd13 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -113,7 +113,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", try { apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) + {{#returnType}} Some(apiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) {{/returnType}} case _ => None } diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 776c0844550..3bcadab73c9 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -148,7 +148,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(apiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) case _ => None } } catch { @@ -190,7 +190,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(apiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) case _ => None } } catch { @@ -229,7 +229,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) + Some(apiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) case _ => None } } catch { @@ -358,7 +358,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[ApiResponse]).asInstanceOf[ApiResponse]) + Some(apiInvoker.deserialize(s, "", classOf[ApiResponse]).asInstanceOf[ApiResponse]) case _ => None } } catch { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 4514108bd77..3f72757f9eb 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -102,7 +102,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) + Some(apiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) case _ => None } } catch { @@ -141,7 +141,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(apiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) case _ => None } } catch { @@ -182,7 +182,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(apiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) case _ => None } } catch { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index 441337d1759..df039c1f7cc 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -225,7 +225,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + Some(apiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) case _ => None } } catch { @@ -271,7 +271,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) + Some(apiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) case _ => None } } catch { From a6b0518bf0108eedfe70bfb4259ef0d8cffd28f6 Mon Sep 17 00:00:00 2001 From: "J. Fiala" Date: Tue, 10 Jan 2017 18:03:51 +0100 Subject: [PATCH 231/269] replace tabs --- .../io/swagger/codegen/DefaultCodegen.java | 24 +++++++++---------- .../languages/AbstractJavaCodegen.java | 14 +++++------ .../languages/JavaJerseyServerCodegen.java | 8 +++---- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index c1daf3ce8ab..3888c9bfbc0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -346,7 +346,7 @@ public class DefaultCodegen { // override with any special handling of the JMustache compiler @SuppressWarnings("unused") public Compiler processCompiler(Compiler compiler) { - return compiler; + return compiler; } // override with any special text escaping logic @@ -1680,7 +1680,7 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { property.isContainer = true; property.isListContainer = true; property.containerType = "array"; @@ -1689,7 +1689,7 @@ public class DefaultCodegen { ArrayProperty ap = (ArrayProperty) p; CodegenProperty cp = fromProperty(property.name, ap.getItems()); updatePropertyForArray(property, cp); - } else if (p instanceof MapProperty) { + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1876,7 +1876,7 @@ public class DefaultCodegen { * @return Codegen Operation object */ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - return fromOperation(path, httpMethod, operation, definitions, null); + return fromOperation(path, httpMethod, operation, definitions, null); } /** @@ -2531,7 +2531,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { - return Collections.emptyList(); + return Collections.emptyList(); } List secs = new ArrayList(schemes.size()); @@ -2555,8 +2555,8 @@ public class DefaultCodegen { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); if (sec.flow == null) { @@ -3191,11 +3191,11 @@ public class DefaultCodegen { // encountered so far and hopefully make it easier for others to add more special // cases in the future. - // better error handling when map/array type is invalid - if (name == null) { - LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); - return "ERROR_UNKNOWN"; - } + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // if the name is just '$', map it to 'value' for the time being. if ("$".equals(name)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index faa08458dfd..12205972765 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -1002,16 +1002,16 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } public boolean convertPropertyToBoolean(String propertyKey) { - boolean booleanValue = false; - if (additionalProperties.containsKey(propertyKey)) { - booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); } return booleanValue; } - - public void writePropertyBack(String propertyKey, boolean value) { - additionalProperties.put(propertyKey, value); - } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index f60ac8ad7b3..99d7f70ee7c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -89,12 +89,12 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen impl } if (additionalProperties.containsKey(USE_BEANVALIDATION)) { - this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); } - if (useBeanValidation) { - writePropertyBack(USE_BEANVALIDATION, useBeanValidation); - } + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); From d7eeb069f2a0fb47e857d1d93c9abd59eb0a8594 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 11 Jan 2017 15:55:51 +0800 Subject: [PATCH 232/269] update 2016 to 2017 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1c52130cf48..82fb0c5c383 100644 --- a/README.md +++ b/README.md @@ -976,7 +976,7 @@ When code is generated from this project, it shall be considered **AS IS** and o License ------- -Copyright 2016 SmartBear Software +Copyright 2017 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From 2e4de0ca1ee60ba85853701cc0c98767212c9dc4 Mon Sep 17 00:00:00 2001 From: Pete Holiday Date: Thu, 12 Jan 2017 03:17:17 -0500 Subject: [PATCH 233/269] Remove unnecessary call to setHost() in the constructor (#4525) * Remove unnecessary call to setHost() in the constructor The default host will be automatically set on the client by the ApiClient constructor. * Updated PHP API Classes corresponding to template updates in #4525. * Additional changes generated by the petstore update unrelated to #4525, but seem to have not been included yet. * Add test to prevent regressions of #4525 --- .../src/main/resources/php/api.mustache | 1 - .../php/SwaggerClient-php/docs/Api/PetApi.md | 2 +- .../docs/Model/ClassModel.md | 10 + .../SwaggerClient-php/docs/Model/OuterEnum.md | 9 + .../php/SwaggerClient-php/lib/Api/FakeApi.php | 1 - .../php/SwaggerClient-php/lib/Api/PetApi.php | 1 - .../SwaggerClient-php/lib/Api/StoreApi.php | 1 - .../php/SwaggerClient-php/lib/Api/UserApi.php | 1 - .../php/SwaggerClient-php/lib/ApiClient.php | 5 + .../SwaggerClient-php/lib/Configuration.php | 34 +++ .../lib/Model/ClassModel.php | 229 ++++++++++++++++++ .../SwaggerClient-php/lib/Model/OuterEnum.php | 51 ++++ .../test/Model/ClassModelTest.php | 93 +++++++ .../test/Model/OuterEnumTest.php | 85 +++++++ .../SwaggerClient-php/tests/PetApiTest.php | 16 ++ 15 files changed, 533 insertions(+), 6 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/ClassModelTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/test/Model/OuterEnumTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 1768ff7ac5e..bfbb6fca373 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -49,7 +49,6 @@ use \{{invokerPackage}}\ObjectSerializer; { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('{{basePath}}'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index b589c11a32a..d99eea4c925 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -389,7 +389,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | **additional_metadata** | **string**| Additional data to pass to server | [optional] - **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] + **file** | **\SplFileObject**| file to upload | [optional] ### Return type diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md new file mode 100644 index 00000000000..3ad025b6ed3 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **string** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 9d13660091f..54522e7a792 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -59,7 +59,6 @@ class FakeApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index efee25ca687..cb902068dd4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -59,7 +59,6 @@ class PetApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 7070313661d..61531c1ada4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -59,7 +59,6 @@ class StoreApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index db404dd8818..31580e1b3c1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -59,7 +59,6 @@ class UserApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 8bda07de03f..51935028b00 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -163,6 +163,11 @@ class ApiClient if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index ca4e62be7ee..8066ae8ac66 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -97,6 +97,13 @@ class Configuration */ protected $curlTimeout = 0; + /** + * Timeout (second) of the HTTP connection, by default set to 0, no timeout + * + * @var string + */ + protected $curlConnectTimeout = 0; + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * @@ -380,6 +387,33 @@ class Configuration return $this->curlTimeout; } + /** + * Sets the HTTP connect timeout value + * + * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] + * + * @return Configuration + */ + public function setCurlConnectTimeout($seconds) + { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + } + + $this->curlConnectTimeout = $seconds; + return $this; + } + + /** + * Gets the HTTP connect timeout value + * + * @return string HTTP connect timeout value + */ + public function getCurlConnectTimeout() + { + return $this->curlConnectTimeout; + } + /** * Sets debug flag * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php new file mode 100644 index 00000000000..74b0aff6da0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php @@ -0,0 +1,229 @@ + 'string' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + '_class' => '_class' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + '_class' => 'setClass' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + '_class' => 'getClass' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['_class'] = isset($data['_class']) ? $data['_class'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properteis are valid + */ + public function valid() + { + return true; + } + + + /** + * Gets _class + * @return string + */ + public function getClass() + { + return $this->container['_class']; + } + + /** + * Sets _class + * @param string $_class + * @return $this + */ + public function setClass($_class) + { + $this->container['_class'] = $_class; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php new file mode 100644 index 00000000000..26c54fd1b2e --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php @@ -0,0 +1,51 @@ +assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } + + // Ensure that API Classes pickup ApiClient defaults to prevent regressions of PR #4525 + public function testHostOverride() + { + $orig_default = Configuration::getDefaultConfiguration(); + $new_default = new Configuration(); + + $new_default->setHost("http://localhost/whatever"); + Configuration::setDefaultConfiguration($new_default); + + $pet_api = new Api\PetApi(); + $pet_host = $pet_api->getApiClient()->getConfig()->getHost(); + $this->assertSame($pet_host, $new_default->getHost()); + + Configuration::setDefaultConfiguration($orig_default); // Reset to original to prevent failure of other tests that rely on this state + } } From 0fb154e9a220e3ec3358893c04dace30c312f62d Mon Sep 17 00:00:00 2001 From: Bartek Kryza Date: Thu, 12 Jan 2017 09:48:25 +0100 Subject: [PATCH 234/269] [Bash] Bash client script generator (#4541) * Initial commit * Remormatted petstore tests * Added Bash codegen to main README.md * Added bash to integration tests * Fixed stdin detection in generated script * Added back ruby module --- .travis.yml | 6 + CONTRIBUTING.md | 1 + README.md | 4 +- bin/bash-petstore.sh | 31 + .../codegen/languages/BashClientCodegen.java | 655 ++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/bash/README.md | 220 ++ .../src/main/resources/bash/README.mustache | 75 + .../resources/bash/bash-completion.mustache | 286 ++ .../src/main/resources/bash/client.mustache | 1106 ++++++ .../resources/bash/zsh-completion.mustache | 301 ++ .../codegen/bash/BashClientOptionsTest.java | 56 + .../io/swagger/codegen/bash/BashTest.java | 158 + .../options/BashClientOptionsProvider.java | 61 + .../src/test/resources/2_0/bash-config.json | 10 + .../src/test/resources/2_0/petstore-bash.json | 1056 ++++++ pom.xml | 13 + .../petstore/bash/.swagger-codegen-ignore | 23 + samples/client/petstore/bash/README.md | 75 + samples/client/petstore/bash/_petstore-cli | 454 +++ samples/client/petstore/bash/petstore-cli | 3312 +++++++++++++++++ .../bash/petstore-cli.bash-completion | 286 ++ samples/client/petstore/bash/pom.xml | 47 + .../petstore/bash/tests/petstore_test.sh | 102 + 24 files changed, 8338 insertions(+), 1 deletion(-) create mode 100755 bin/bash-petstore.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/bash/README.md create mode 100644 modules/swagger-codegen/src/main/resources/bash/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache create mode 100644 modules/swagger-codegen/src/main/resources/bash/client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java create mode 100644 modules/swagger-codegen/src/test/resources/2_0/bash-config.json create mode 100644 modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json create mode 100644 samples/client/petstore/bash/.swagger-codegen-ignore create mode 100644 samples/client/petstore/bash/README.md create mode 100644 samples/client/petstore/bash/_petstore-cli create mode 100755 samples/client/petstore/bash/petstore-cli create mode 100644 samples/client/petstore/bash/petstore-cli.bash-completion create mode 100644 samples/client/petstore/bash/pom.xml create mode 100644 samples/client/petstore/bash/tests/petstore_test.sh diff --git a/.travis.yml b/.travis.yml index 68a526cf1b4..e0290b10205 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,12 @@ before_install: - docker pull swaggerapi/petstore - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - docker ps -a + # Add bats test framework and cURL for Bash script integration tests + - sudo add-apt-repository ppa:duggan/bats --yes + - sudo apt-get update -qq + - sudo apt-get install -qq bats + - sudo apt-get install -qq curl + # show host table to confirm petstore.swagger.io is mapped to localhost - cat /etc/hosts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b187c39192c..83166fa1a53 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,7 @@ For a list of variables available in the template, please refer to this [page](h ### Style guide Code change should conform to the programming style guide of the respective languages: - Android: https://source.android.com/source/code-style.html +- Bash: https://github.com/bahamas10/bash-style-guide - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - Clojure: https://github.com/bbatsov/clojure-style-guide diff --git a/README.md b/README.md index 82fb0c5c383..e9c68acc931 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: **ActionScript**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) +- **API clients**: **ActionScript**, **Bash**,**C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) - **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** @@ -463,6 +463,7 @@ AndroidClientCodegen.java AspNet5ServerCodegen.java AspNetCoreServerCodegen.java AsyncScalaClientCodegen.java +BashClientCodegen.java CSharpClientCodegen.java ClojureClientCodegen.java CsharpDotNet2ClientCodegen.java @@ -891,6 +892,7 @@ Swagger Codegen core team members are contributors who have been making signific Here is a list of template creators: * API Clients: * Akka-Scala: @cchafer + * Bash: @bkryza * C++ REST: @Danielku15 * C# (.NET 2.0): @who * Clojure: @xhh diff --git a/bin/bash-petstore.sh b/bin/bash-petstore.sh new file mode 100755 index 00000000000..9988a1157f2 --- /dev/null +++ b/bin/bash-petstore.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" +args="$@ generate -t modules/swagger-codegen/src/main/resources/bash -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l bash -o samples/client/petstore/bash -c modules/swagger-codegen/src/test/resources/2_0/bash-config.json" + +java $JAVA_OPTS -jar $executable $args diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java new file mode 100644 index 00000000000..e96fea31da7 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java @@ -0,0 +1,655 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; +import io.swagger.models.parameters.*; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.*; +import java.io.File; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { + + protected String apiVersion = "1.0.0"; + + protected String curlOptions; + protected boolean processMarkdown = false; + protected String scriptName = "client.sh"; + protected boolean generateBashCompletion = false; + protected boolean generateZshCompletion = false; + protected String hostEnvironmentVariable; + protected String basicAuthEnvironmentVariable; + protected String apiKeyAuthEnvironmentVariable; + + + public static final String CURL_OPTIONS = "curlOptions"; + public static final String PROCESS_MARKDOWN = "processMarkdown"; + public static final String SCRIPT_NAME = "scriptName"; + public static final String + GENERATE_BASH_COMPLETION = "generateBashCompletion"; + public static final String + GENERATE_ZSH_COMPLETION = "generateZshCompletion"; + public static final String + HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; + public static final String + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable"; + public static final String + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + /** + * Configures a friendly name for the generator. This will be used by + * the generator to select the library with the -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "bash"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a Bash client script based on cURL."; + } + + public BashClientCodegen() { + super(); + + /** + * Set the output folder here + */ + outputFolder = "generated-code/bash"; + + /** + * No model files. + */ + modelTemplateFiles.clear(); + + + /** + * No API files. + */ + apiTemplateFiles.clear(); + + + /** + * Templates location for client script and bash completion template. + */ + templateDir = "bash"; + + + /** + * Allow the user to force the script to always include certain cURL + * comamnds + */ + cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); + cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, + "Convert all Markdown Markup into terminal formatting")); + cliOptions.add(CliOption.newString(SCRIPT_NAME, + "The name of the script that will be generated "+ + "(e.g. petstore-cli)")); + cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, + "Whether to generate the Bash completion script")); + cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, + "Whether to generate the Zsh completion script")); + cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where host can be defined "+ + "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); + cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where username and password " + + + "can be defined (e.g. PETSTORE_CREDS='username:password')")); + cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where API key " + + + "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); + + /** + * Bash reserved words. + */ + reservedWords = new HashSet ( + Arrays.asList( + "case", + "do", + "done", + "elif", + "else", + "esac", + "fi", + "for", + "function", + "if", + "in", + "select", + "then", + "time", + "until", + "while") + ); + + typeMapping.clear(); + typeMapping.put("array", "array"); + typeMapping.put("map", "map"); + typeMapping.put("List", "array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("number", "integer"); + typeMapping.put("DateTime", "string"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("char", "string"); + typeMapping.put("double", "float"); + typeMapping.put("object", "map"); + typeMapping.put("integer", "integer"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("binary", "binary"); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files. + */ + additionalProperties.put("apiVersion", apiVersion); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet(); + } + + + @Override + public void processOpts() { + super.processOpts(); + String curlopts = ""; + + if (additionalProperties.containsKey(CURL_OPTIONS)) { + setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); + additionalProperties.put("x-codegen-curl-options", curlopts); + } + + if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { + setProcessMarkdown( + Boolean.parseBoolean( + additionalProperties.get(PROCESS_MARKDOWN).toString())); + } + + if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { + setGenerateBashCompletion( + Boolean.parseBoolean( + additionalProperties.get(GENERATE_BASH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { + setGenerateZshCompletion( + Boolean.parseBoolean( + additionalProperties.get(GENERATE_ZSH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(SCRIPT_NAME)) { + setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); + } + additionalProperties.put("x-codegen-script-name", scriptName); + + if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { + setHostEnvironmentVariable( + additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); + } + + if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setBasicAuthEnvironmentVariable( + additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); + } + + if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setApiKeyAuthEnvironmentVariable( + additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); + } + + supportingFiles.add(new SupportingFile( + "client.mustache", "", scriptName)); + supportingFiles.add(new SupportingFile( + "bash-completion.mustache", "", scriptName+".bash-completion")); + supportingFiles.add(new SupportingFile( + "zsh-completion.mustache", "", "_"+scriptName)); + supportingFiles.add(new SupportingFile( + "README.mustache", "", "README.md")); + } + + public void setCurlOptions(String curlOptions) { + this.curlOptions = curlOptions; + } + + public void setProcessMarkdown(boolean processMarkdown) { + this.processMarkdown = processMarkdown; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public void setGenerateBashCompletion(boolean generateBashCompletion) { + this.generateBashCompletion = generateBashCompletion; + } + + public void setGenerateZshCompletion(boolean generateZshCompletion) { + this.generateZshCompletion = generateZshCompletion; + } + + public void setHostEnvironmentVariable(String hostEnvironmentVariable) { + this.hostEnvironmentVariable = hostEnvironmentVariable; + } + + public void setBasicAuthEnvironmentVariable(String + basicAuthEnvironmentVariable) { + this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; + } + + public void setApiKeyAuthEnvironmentVariable(String + apiKeyAuthEnvironmentVariable) { + this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; + } + + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reseved words. + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated. + */ + public String modelFileFolder() { + return outputFolder; + } + + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated. + */ + @Override + public String apiFileFolder() { + return outputFolder; + } + + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in + * a `Property` into either language specific types via `typeMapping` or into + * complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return type; + } + else + type = swaggerType; + return toModelName(type); + } + + + /** + * Convert Swagger Parameter object to Codegen Parameter object + * + * @param param Swagger parameter object + * @param imports set of imports for library/package/module + * @return Codegen Parameter object + */ + @Override + public CodegenParameter fromParameter(Parameter param, Set imports) { + + CodegenParameter p = super.fromParameter(param, imports); + + if(param instanceof BodyParameter) { + + Model model = ((BodyParameter)param).getSchema(); + + } + else if(param instanceof SerializableParameter) { + + /** + * Currently it's not possible to specify in the codegen other collection + * formats than 'multi' + */ + SerializableParameter sparam = (SerializableParameter)param; + + if( sparam.getCollectionFormat() != null + && !sparam.getCollectionFormat().isEmpty()) { + + String collectionFormat = sparam.getCollectionFormat(); + + if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) { + p.vendorExtensions.put("x-codegen-collection-max-items", + sparam.getMaxItems()); + } + + if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) { + p.vendorExtensions.put("x-codegen-collection-min-items", + sparam.getMinItems()); + } + + if( (collectionFormat.equals("multi")) + && (param.getIn().equals("query")) ) { + + /** + * 'multi' is only supported for query parameters + */ + p.vendorExtensions.put("x-codegen-collection-multi", true); + + } + else if(collectionFormat.equals("csv")) { + p.vendorExtensions.put("x-codegen-collection-csv", true); + } + else if(collectionFormat.equals("ssv")) { + p.vendorExtensions.put("x-codegen-collection-ssv", true); + } + else if(collectionFormat.equals("tsv")) { + p.vendorExtensions.put("x-codegen-collection-tsv", true); + } + else if(collectionFormat.equals("pipes")) { + p.vendorExtensions.put("x-codegen-collection-pipes", true); + } + else { + /** Unsupported collection format */ + } + + } + + } + + return p; + + } + + /** + * Override with any special text escaping logic + */ + @SuppressWarnings("static-method") + public String escapeText(String input) { + if (input == null) { + return input; + } + + /** + * remove standalone '\' + * + * replace " with \" + * outter unescape to retain the original multi-byte characters + */ + String result = escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(input).replace("\\/", "/")) + .replace("\\", "\\\\") + .replace("\"", "\\\"")); + + if(this.processMarkdown) { + + /** + * Convert markdown strong **Bold text** and __Bold text__ + * to bash bold control sequences (tput bold) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + + result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + /** + * Convert markdown *Italics text* and _Italics text_ to bash dim + * control sequences (tput dim) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + + result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + + + /** + * Convert all markdown section 1 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown section 2 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown section 3 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown code blocks into --- delimited sections + */ + result = result.replaceAll("(?m)\\s*```.*$", + "\n---"); + + result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", + "\n---"); + + /** + * Remove any trailing new line at the end of the string + */ + result = result.replaceAll("\\s+$", ""); + } + + return result; + } + + @Override + public String escapeQuotationMark(String input) { + return input; + } + + /** + * Override with any special text escaping logic to handle unsafe + * characters so as to avoid code injection. + * + * @param input String to be cleaned up + * @return string with unsafe characters removed or escaped + */ + public String escapeUnsafeCharacters(String input) { + + /** + * Replace backticks with normal single quotes. + */ + String result = input.replaceAll("`", "'"); + + return result; + } + + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, + Operation operation, + Map definitions, + Swagger swagger) { + + CodegenOperation op = super.fromOperation(path, httpMethod, operation, + definitions, swagger); + + /** + * Check if the operation has a Bash codegen specific description + * for help + */ + if(op.vendorExtensions.containsKey("x-bash-codegen-description")) { + String bash_description + = (String)op.vendorExtensions.get("x-bash-codegen-description"); + + op.vendorExtensions.put("x-bash-codegen-description", + escapeText(bash_description)); + } + + /** + * Check if operation has an 'x-code-samples' vendor extension with + * Shell example + */ + if(op.vendorExtensions.containsKey("x-code-samples")) { + + List codesamples = (List)op.vendorExtensions.get("x-code-samples"); + + for (Object codesample : codesamples) { + ObjectNode codesample_object = (ObjectNode)codesample; + + if((codesample_object.get("lang").asText()).equals("Shell")) { + + op.vendorExtensions.put("x-bash-codegen-sample", + escapeUnsafeCharacters( + codesample_object.get("source").asText())); + + } + + } + } + + for (CodegenParameter p : op.bodyParams) { + if(p.dataType != null && definitions.get(p.dataType) != null) { + /** + * If the operation produces Json and has nonempty example + * try to reformat it. + */ + if(operation.getConsumes() != null + && operation.getConsumes().contains("application/json") + && definitions.get(p.dataType).getExample() != null) { + + ObjectMapper mapper = new ObjectMapper(); + try { + p.vendorExtensions.put( + "x-codegen-body-example", + mapper.writerWithDefaultPrettyPrinter().writeValueAsString( + definitions.get(p.dataType).getExample())); + } + catch(JsonProcessingException e) { + e.printStackTrace(); + } + } + else { + /** + * Otherwise present whatever is provided as example + */ + p.vendorExtensions.put( + "x-codegen-body-example", + definitions.get(p.dataType).getExample()); + } + } + } + + return op; + + } + + /** + * Preprocess original properties from the Swagger definition where necessary. + * + * @param swagger [description] + */ + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } + + if(swagger.getInfo() != null + && swagger.getInfo().getVendorExtensions()!=null) { + String bash_codegen_app_description + = (String)swagger.getInfo().getVendorExtensions() + .get("x-bash-codegen-description"); + + if(bash_codegen_app_description != null) { + + bash_codegen_app_description + = escapeText(bash_codegen_app_description); + + additionalProperties.put("x-bash-codegen-app-description", + bash_codegen_app_description); + + } + } + + } + +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 02f5ce9c05d..9b36d8c527a 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -2,6 +2,7 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AspNetCoreServerCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen +io.swagger.codegen.languages.BashClientCodegen io.swagger.codegen.languages.ConfluenceWikiGenerator io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.CppRestClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/bash/README.md b/modules/swagger-codegen/src/main/resources/bash/README.md new file mode 100644 index 00000000000..9528032e8fa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/README.md @@ -0,0 +1,220 @@ +# Bash script generator for Swagger Codegen + +## Overview +This is a Bash client script codegen. + +The codegen creates a standalone, single-file Bash script client to quickly test and access Swagger annotated REST services. The generated script uses underneath [cURL](https://curl.haxx.se) to make actual REST calls. + +The generated Bash script has only 2 dependencies: +- Bash (>= 4.3) +- cURL + +## Features +- Fully automatic generation of a client Bash script to access any Swagger-defined REST service +- Generation of Bash and Zsh completion scripts +- All valid cURL options can be passed directly +- Preview of cURL commands to execute each operation using `--dry-run` option +- Complete help for entire service as well as for each operation +- No external dependencies besides Bash and cURL + +## Usage + +### Generating Bash client for REST service + +Get the sources: +```shell +$ git clone https://github.com/swagger-api/swagger-codegen +``` + +Build the codegen: +```shell +$ mvn assembly:assembly -DdescriptorId=jar-with-dependencies +``` + +Define custom codegen properties in a Json file, e.g.: +```shell +{ + "processMarkdown": true, + "curlOptions": "-sS --tlsv1.2", + "scriptName": "petstore-cli", + "generateBashCompletion": true, + "generateZshCompletion": true, + "hostEnvironmentVariable": "PETSTORE_HOST", + "basicAuthEnvironmentVariable": "PETSTORE_BASIC_AUTH", + "apiKeyAuthEnvironmentVariable": "PETSTORE_API_KEY" +} +``` + +Generate the client: +```shell +$ java -cp target/bash-swagger-codegen-1.0.0.jar io.swagger.codegen.SwaggerCodegen generate -l bash -i http://petstore.swagger.io/v2/swagger.json -o output -c resources/example-config.json + +$ chmod +x output/petstore-cli +``` + +Enjoy: +```shell +$ output/petstore-cli -h + +Swagger Petstore command line client (API version 1.0.0) + +Usage + + petstore-cli [-h|--help] [-V|--version] [--about] [] + [-ac|--accept ] [-ct,--content-type ] + [--host ] [--dry-run] [-h|--help] [] + [] [] + + - - endpoint of the REST service without basepath + Can also be specified in PETSTORE_HOST environment variable. + - - any valid cURL options can be passed before + - - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - - HTTP headers can be passed in the form HEADER:VALUE + - - REST operation parameters can be passed in the following + forms: + * KEY=VALUE - path or query parameters + - - simple JSON body content (first level only) can be build + using the following arguments: + * KEY==VALUE - body parameters which will be added to body + JSON as '{ ..., "KEY": "VALUE", ... }' + * KEY:=VALUE - body parameters which will be added to body + JSON as '{ ..., "KEY": VALUE, ... }' + +Authentication methods + + - Api-key - add 'api_key:' after + or export PETSTORE_API_KEY='' + - OAuth2 (flow: implicit) + Authorization URL: + * http://petstore.swagger.io/oauth/dialog + Scopes: + * write:pets - modify pets in your account + * read:pets - read your pets + +Operations (grouped by tags) + +[pet] + addPet Add a new pet to the store + deletePet Deletes a pet + findPetsByStatus Finds Pets by status + findPetsByTags Finds Pets by tags + getPetById Find pet by ID + updatePet Update an existing pet + updatePetWithForm Updates a pet in the store with form data + uploadFile uploads an image + +[store] + deleteOrder Delete purchase order by ID + getInventory Returns pet inventories by status + getOrderById Find purchase order by ID + placeOrder Place an order for a pet + +[user] + createUser Create user + createUsersWithArrayInput Creates list of users with given input array + createUsersWithListInput Creates list of users with given input array + deleteUser Delete user + getUserByName Get user by user name + loginUser Logs user into the system + logoutUser Logs out current logged in user session + updateUser Updated user + +Options + -h,--help Print this help + -V,--version Print API version + --about Print the information about service + --host Specify the host URL + (e.g. 'https://petstore.swagger.io') + --force Force command invocation in spite of missing + required parameters or wrong content type + --dry-run Print out the cURL command without + executing it + -ac,--accept Set the 'Accept' header in the request + -ct,--content-type Set the 'Content-type' header in + the request +``` + +Client generator takes several specific configuration options: +* *processMarkdown* - [boolean] if set to `true`, all text (descriptions) in the Swagger specification will be treated as Markdown and converted to terminal formatting commands, +* *curlOptions* - [string] a list of default cURL options that will be added to each command +* *scriptName* - [string] the name of the target script, necessary when building Bash completion script +* *generateBashCompletion* - [boolean] if set to `true` the Bash completion script will be generated +* *generateZshCompletion* - [boolean] if set to `true` the Bash completion script will be generated +* *hostEnvironmentVariable* - [string] the name of environment variable to search for default host +* *basicAuthEnvironmentVariable* - [string] the name of environment variable to search for default basic auth credentials +* *apiKeyAuthEnvironmentVariable* - [string] the name of environment variable to search for default api key + +These options can be specified in a Json file used when running the codegen using option `-c` (see [example](resources/example-config.json)). + +### Using the generated Bash script + +```shell +# Print the list of operations available on the service +$ petstore-cli --help + +# Print the service description +$ petstore-cli --about + +# Print detailed information about specific operation +$ petstore-cli addPet --help + +# Call REST API operation +$ echo '{"id":891,"name":"lucky","status":"available"}' | petstore-cli --host http://petstore.swagger.io --content-type json addPet - + +{"id":891,"name":"lucky","photoUrls":[],"tags":[],"status":"available"} + +# The above is equivalent to +$ petstore-cli --host http://petstore.swagger.io --content-type json --accept xml addPet id:=891 name==lucky status==available + +891luckyavailable + + +# Preview the cURL command without actually executing it +# The above is equivalent to +$ petstore-cli --host http://petstore.swagger.io --content-type json --dry-run addPet id:=891 name==lucky status==available + +curl -sS --tlsv1.2 -H 'Content-type: application/json' -X POST -d '{"name": "lucky", "status": "available", "id": 891}' "http://petstore.swagger.io/v2/pet" +``` + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source output/petstore-cli.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp output/petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_{{scriptName}}` file (e.g. _petstore-cli) must be copied to one of the folders under `$fpath` variable. + + +## TODO +- [ ] Add enum values for parameters shell completion +- [ ] Wrap handling of errors returned by the service, using comments defined in the Swagger specification +- [ ] Improve `--help` and `--about` formatting +- [ ] Add support to bash 4.0-4.2 (currently must be >= 4.3) +- [ ] Add manpage generation +- [ ] Add support for form data +- [ ] Move todos to Github issues diff --git a/modules/swagger-codegen/src/main/resources/bash/README.mustache b/modules/swagger-codegen/src/main/resources/bash/README.mustache new file mode 100644 index 00000000000..d60bb0f201d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/README.mustache @@ -0,0 +1,75 @@ +# {{appName}} Bash client + +## Overview +This is a Bash client script for accessing {{appName}} service. + +The script uses cURL underneath for making all REST calls. + +## Usage + +```shell +# Make sure the script has executable rights +$ chmod u+x {{scriptName}} + +# Print the list of operations available on the service +$ ./{{scriptName}} -h + +# Print the service description +$ ./{{scriptName}} --about + +# Print detailed information about specific operation +$ ./{{scriptName}} -h + +# Make GET request +./{{scriptName}} --host http://: --accept xml = : + +# Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password +{{scriptName}} -k -sS --tlsv1.2 --host https:// -u : --accept xml = : + +# Make POST request +$ echo '' | {{scriptName}} --host --content-type json - + +# Make POST request with simple JSON content, e.g.: +# { +# "key1": "value1", +# "key2": "value2", +# "key3": 23 +# } +$ echo '' | {{scriptName}} --host --content-type json key1==value1 key2=value2 key3:=23 - + +# Preview the cURL command without actually executing it +$ {{scriptName}} --host http://: --dry-run + +``` + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source {{scriptName}}.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_{{scriptName}}` Zsh completion file must be copied to one of the folders under `$FPATH` variable. + diff --git a/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache new file mode 100644 index 00000000000..c184a82456d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache @@ -0,0 +1,286 @@ +# {{scriptName}} completion -*- shell-script -*- + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: {{generatedDate}} +# ! +# ! +# ! System wide installation: +# ! +# ! $ sudo cp {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} +# ! +# ! +# ! User home installation (add this line to .bash_profile): +# ! +# ! [ -r ~/{{scriptName}}.bash-completion ] && source ~/{{scriptName}}.bash-completion +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + + +__osx_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword +} + + +_{{scriptName}}() +{ + local cur + local prev + local words + local cword + + #words="${COMP_WORDS}" + #cword="${COMP_CWORD}" + #prev="${COMP_WORDS[COMP_CWORD-1]}" + #cur="${COMP_WORDS[COMP_CWORD]}" + + # The reference of currently selected REST operation + local operation="" + + # The list of available operation in the REST service + # It's modelled as an associative array for efficient key lookup + declare -A operations +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + operations["{{operationId}}"]=1 +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # An associative array of operations to their parameters + # Only include path, query and header parameters + declare -A operation_parameters +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + operation_parameters["{{operationId}}"]="{{#pathParams}}{{baseName}}= {{/pathParams}}{{#queryParams}}{{baseName}}= {{/queryParams}}{{#headerParams}}{{baseName}}: {{/headerParams}}" +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # An associative array of possible values for enum parameters + declare -A operation_parameters_enum_values +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +{{#pathParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{#isEnum}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="" +{{/isEnum}} +{{/pathParams}} +{{#queryParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{/queryParams}} +{{#headerParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{/headerParams}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # + # Check if the _init_completion function is available, which is + # available since bash-completion 1.4 + # + if declare -F _init_completions >/dev/null 2>&1; then + _init_completion -s || return + else + __osx_init_completion || return + fi + + + # Check if operation is already in the command line provided + for word in "${words[@]}"; do + if [[ -n $word && ${operations[$word]} ]]; then + operation="${word}" + fi + done + + if [[ -z $operation ]]; then + case $prev in + --ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\ + --ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\ + --help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\ + --mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\ + --pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\ + --range|-X|--request|--retry|--retry-delay|--retry-max-time|\ + --socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\ + --time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\ + --write-out|--resolve|--tlsuser|--tlspassword|--about) + return + ;; + -K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\ + --key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\ + --trace-ascii|--netrc-file) + _filedir + return + ;; + --cacert|-E|--cert) + _filedir '@(c?(e)rt|cer|pem|der)' + return + ;; + --capath) + _filedir -d + return + ;; + --cert-type|--key-type) + COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) ) + return + ;; + --crlfile) + _filedir crl + return + ;; + -d|--data|--data-ascii|--data-binary|--data-urlencode) + if [[ $cur == \@* ]]; then + cur=${cur:1} + _filedir + COMPREPLY=( "${COMPREPLY[@]/#/@}" ) + fi + return + ;; + --delegation) + COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) ) + return + ;; + --engine) + COMPREPLY=( $( compgen -W 'list' -- "$cur" ) ) + return + ;; + --ftp-method) + COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) ) + return + ;; + --ftp-ssl-ccc-mode) + COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) ) + return + ;; + --interface) + _available_interfaces -a + return + ;; + -x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname) + _known_hosts_real + return + ;; + --pubkey) + _filedir pub + return + ;; + --stderr) + COMPREPLY=( $( compgen -W '-' -- "$cur" ) ) + _filedir + return + ;; + --tlsauthtype) + COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) ) + return + ;; + --host) + COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) ) + return + ;; + -ct|--content-type|-ac|--accept) + COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) ) + return + ;; + esac + fi + + # + # Complete the server address based on ~/.ssh/known_hosts + # and ~/.ssh/config + # + # \todo Fix - cur matches only '//' when $prev is ':' + # + if [[ "$cur" == "http://" || "$cur" == "https://" ]]; then + COMPREPLY=() + local comp_ssh_hosts=`cat ~/.ssh/known_hosts | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ; + cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}'` + COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur)) + return + fi + + # + # Complete the {{scriptName}} and cURL's arguments + # + if [[ $cur == -* ]]; then + COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) ) + return + fi + + # + # If the argument starts with a letter this could be either an operation + # or an operation parameter + # When $cur is empty, suggest the list of operations by default + # + if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then + # If operation has not been yet selected, suggest the list of operations + # otherwise suggest arguments of this operation as declared in the + # Swagger specification + if [[ -z $operation ]]; then + COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) + else + COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + fi + return + fi + +} && +complete -F _{{scriptName}} {{scriptName}} + +# ex: ts=4 sw=4 et filetype=sh \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/bash/client.mustache b/modules/swagger-codegen/src/main/resources/bash/client.mustache new file mode 100644 index 00000000000..5a11334690d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/client.mustache @@ -0,0 +1,1106 @@ +#!/usr/bin/env bash + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: {{generatedDate}} +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# +# This is a Bash client for {{appName}}. +# +# LICENSE: +# {{licenseUrl}} +# +# CONTACT: +# {{infoEmail}} +# +# MORE INFORMATION: +# {{#externalDocs}}{{url}}{{/externalDocs}} +# + + +############################################################################### +# +# Global variables +# +############################################################################### + +## +# The filename of this script for help messages +script_name=`basename "$0"` + +## +# Map for headers passed after operation as KEY:VALUE +declare -A header_arguments + + +## +# Map for operation parameters passed after operation as PARAMETER=VALUE +# These will be mapped to appropriate path or query parameters +# The values in operation_parameters are arrays, so that multiple values +# can be provided for the same parameter if allowed by API specification +declare -A operation_parameters + +## +# This array stores the minimum number of required occurences for parameter +# 0 - optional +# 1 - required +declare -A operation_parameters_minimum_occurences +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_minimum_occurences["{{operationId}}:::{{baseName}}"]={{#required}}{{#vendorExtensions}}{{#x-codegen-collection-min-items}}{{x-codegen-collection-min-items}}{{/x-codegen-collection-min-items}}{{^x-codegen-collection-min-items}}1{{/x-codegen-collection-min-items}}{{/vendorExtensions}}{{^vendorExtensions}}1{{/vendorExtensions}}{{/required}}{{^required}}0{{/required}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +## +# This array stores the maximum number of allowed occurences for parameter +# 1 - single value +# 2 - 2 values +# N - N values +# 0 - unlimited +declare -A operation_parameters_maximum_occurences +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_maximum_occurences["{{operationId}}:::{{baseName}}"]={{#vendorExtensions}}{{#x-codegen-collection-max-items}}{{x-codegen-collection-max-items}}{{/x-codegen-collection-max-items}}{{^x-codegen-collection-max-items}}0{{/x-codegen-collection-max-items}}{{/vendorExtensions}}{{^vendorExtensions}}0{{/vendorExtensions}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +## +# The type of collection for specifying multiple values for parameter: +# - multi, csv, ssv, tsv +declare -A operation_parameters_collection_type +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_collection_type["{{operationId}}:::{{baseName}}"]={{#isContainer}}{{#vendorExtensions}}{{#x-codegen-collection-multi}}"multi"{{/x-codegen-collection-multi}}{{#x-codegen-collection-csv}}"csv"{{/x-codegen-collection-csv}}{{#x-codegen-collection-tsv}}"tsv"{{/x-codegen-collection-tsv}}{{#x-codegen-collection-ssv}}"ssv"{{/x-codegen-collection-ssv}}{{/vendorExtensions}}{{^vendorExtensions}}""{{/vendorExtensions}}{{/isContainer}}{{^isContainer}}""{{/isContainer}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + +## +# Map for body parameters passed after operation as +# PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE +# These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) +declare -A body_parameters + +## +# These arguments will be directly passed to cURL +curl_arguments="{{x-codegen-curl-options}}" + +## +# The host for making the request +host="{{#x-codegen-host-env}}${{x-codegen-host-env}}{{/x-codegen-host-env}}" + +## +# The user credentials for basic authentication +basic_auth_credential="{{#x-codegen-basicauth-env}}${{x-codegen-basicauth-env}}{{/x-codegen-basicauth-env}}" + +## +# The user API key +apikey_auth_credential="{{#x-codegen-apikey-env}}${{x-codegen-apikey-env}}{{/x-codegen-apikey-env}}" + +## +# If true, the script will only output the actual cURL command that would be +# used +print_curl=false + +## +# The operation ID passed on the command line +operation="" + +## +# The provided Accept header value +header_accept="" + +## +# The provided Content-type header value +header_content_type="" + +## +# If there is any body content on the stdin pass it to the body of the request +body_content_temp_file="" + +## +# If this variable is set to true, the request will be performed even +# if parameters for required query, header or body values are not provided +# (path parameters are still required). +force=false + +## +# Declare some mime types abbreviations for easier content-type and accepts +# headers specification +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +############################################################################## +# +# Escape special URL characters +# Based on table at http://www.w3schools.com/tags/ref_urlencode.asp +# +############################################################################## +url_escape() { + local raw_url="$1" + + value=$(sed -e 's/ /%20/g' \ + -e 's/!/%21/g' \ + -e 's/"/%22/g' \ + -e 's/#/%23/g' \ + -e 's/\&/%26/g' \ + -e 's/'\''/%28/g' \ + -e 's/(/%28/g' \ + -e 's/)/%29/g' \ + -e 's/:/%3A/g' \ + -e 's/?/%3F/g' <<<$raw_url); + + echo $value +} + +############################################################################## +# +# Lookup the mime type abbreviation in the mime_type_abbreviations array. +# If not present assume the user provided a valid mime type +# +############################################################################## +lookup_mime_type() { + local mime_type=$1 + + if [[ ${mime_type_abbreviations[$mime_type]} ]]; then + echo ${mime_type_abbreviations[$mime_type]} + else + echo $1 + fi +} + +############################################################################## +# +# Converts an associative array into a list of cURL header +# arguments (-H "KEY: VALUE") +# +############################################################################## +header_arguments_to_curl() { + local headers_curl="" + local api_key_header="" + local api_key_header_in_cli="" +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + api_key_header="{{keyParamName}}" +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + + for key in "${!header_arguments[@]}"; do + headers_curl+="-H \"${key}: ${header_arguments[${key}]}\" " + if [[ "${key}XX" == "${api_key_header}XX" ]]; then + api_key_header_in_cli="YES" + fi + done +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + # + # If the api_key was not provided in the header, try one from the + # environment variable + # + if [[ -z $api_key_header_in_cli && -n $apikey_auth_credential ]]; then + headers_curl+="-H \"${api_key_header}: ${apikey_auth_credential}\"" + fi +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + headers_curl+=" " + + echo "${headers_curl}" +} + +############################################################################## +# +# Converts an associative array into a simple JSON with keys as top +# level object attributes +# +# \todo Add convertion of more complex attributes using paths +# +############################################################################## +body_parameters_to_json() { + local body_json="-d '{" + local body_parameter_count=${#body_parameters[@]} + local count=0 + for key in "${!body_parameters[@]}"; do + body_json+="\"${key}\": ${body_parameters[${key}]}" + if [[ $count -lt $body_parameter_count-1 ]]; then + body_json+=", " + fi + count+=1 + done + body_json+="}'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_json}" + fi +} + +############################################################################## +# +# Check if provided parameters match specification requirements +# +############################################################################## +validate_request_parameters() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + # Now append query parameters - if any + if [[ ${#query_params[@]} -gt 0 ]]; then + path_template+="?" + fi + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + if [[ "${operation_parameters_collection_type[${operation}:::${qparam}]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + path_template+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="," + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+=" " + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="\t" + fi + vcount+=1 + done + else + echo -e "" + echo -e "Error: Unsupported collection format " + echo -e "" + exit 1 + fi + + + if [[ $count -lt $query_parameter_count-1 ]]; then + path_template+="&" + fi + count+=1 + done + +} + + + +############################################################################## +# +# Build request path including query parameters +# +############################################################################## +build_request_path() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + local query_request_part="" + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + local parameter_value="" + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + # + # Append parameters without specific cardinality + # + if [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'mutli' collections i.e. param=value1¶m=value2&... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'csv' collections i.e. param=value1,value2,... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="," + fi + vcount+=1 + done + # + # Append parameters specified as 'ssv' collections i.e. param="value1 value2 ..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+=" " + fi + vcount+=1 + done + # + # Append parameters specified as 'tsv' collections i.e. param="value1\tvalue2\t..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="\t" + fi + vcount+=1 + done + fi + + if [[ -n "${parameter_value}" ]]; then + query_request_part+="${parameter_value}" + fi + + if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then + query_request_part+="&" + fi + + count+=1 + + done + + + # Now append query parameters - if any + if [[ -n "${query_request_part}" ]]; then + path_template+="?$(echo ${query_request_part} | sed s'/&$//')" + fi + + echo $path_template +} + + + +############################################################################### +# +# Print main help message +# +############################################################################### +print_help() { +cat <$(tput sgr0)] + [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] + + - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath +{{#x-codegen-host-env}} Can also be specified in {{x-codegen-host-env}} environment variable.{{/x-codegen-host-env}} + - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + forms: + * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' + +EOF +{{#hasAuthMethods}} + echo -e "$(tput bold)$(tput setaf 7)Authentication methods$(tput sgr0)" + echo -e "" +{{#authMethods}} +{{#isBasic}} + echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" + {{#x-codegen-basicauth-env}}echo -e " or export $(tput setaf 1){{x-codegen-basicauth-env}}=':'$(tput sgr0)"{{/x-codegen-basicauth-env}} +{{/isBasic}} +{{#isApiKey}} +{{#isKeyInHeader}} + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1){{keyParamName}}:$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" +{{/isKeyInHeader}} +{{#isKeyInQuery}} + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1){{keyParamName}}=$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" +{{/isKeyInQuery}} + {{#x-codegen-apikey-env}}echo -e " or export $(tput setaf 1){{x-codegen-apikey-env}}=''$(tput sgr0)"{{/x-codegen-apikey-env}} +{{/isApiKey}} +{{#isOAuth}} + echo -e " - $(tput setaf 5)OAuth2 (flow: {{flow}})$(tput sgr0)" + echo -e " Authorization URL: " + echo -e " * {{authorizationUrl}}" + echo -e " Scopes:" +{{#scopes}} + echo -e " * {{scope}} - {{description}}" +{{/scopes}} +{{/isOAuth}} +{{/authMethods}} + echo "" +{{/hasAuthMethods}} + echo -e "$(tput bold)$(tput setaf 7)Operations (grouped by tags)$(tput sgr0)" +{{#apiInfo}} +{{#apis}} + echo "" + echo -e "$(tput bold)$(tput setaf 7)[{{classVarName}}]$(tput sgr0)" +read -d '' ops <$(tput sgr0)\t\t\t\tSpecify the host URL " +{{#swagger}} +{{#host}}echo -e " \t\t\t\t(e.g. 'https://{{host}}')"{{/host}} +{{^host}}echo -e " \t\t\t\t(e.g. 'https://127.0.0.1:8080')"{{/host}} +{{/swagger}} + echo -e " --force\t\t\t\tForce command invocation in spite of missing" + echo -e " \t\t\t\trequired parameters or wrong content type" + echo -e " --dry-run\t\t\t\tPrint out the cURL command without" + echo -e " \t\t\t\texecuting it" + echo -e " -ac,--accept $(tput setaf 3)$(tput sgr0)\t\tSet the 'Accept' header in the request" + echo -e " -ct,--content-type $(tput setaf 3)$(tput sgr0)\tSet the 'Content-type' header in " + echo -e " \tthe request" + echo "" +} + + +############################################################################## +# +# Print REST service description +# +############################################################################## +print_about() { + echo "" + echo -e "$(tput bold)$(tput setaf 7){{appName}} command line client (API version {{#swagger}}{{#info}}{{version}}{{/info}}{{/swagger}})$(tput sgr0)" + echo "" + echo -e "License: {{#swagger}}{{#info}}{{#license}}{{name}}{{/license}}{{/info}}{{/swagger}}" + echo -e "Contact: {{#swagger}}{{#info}}{{#contact}}{{email}}{{/contact}}{{/info}}{{/swagger}}" + echo "" +read -d '' appdescription </dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } +type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } +type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' installed."; exit 1; } + +# +# Process command line +# +# Pass all arguemnts before 'operation' to cURL except the ones we override +# +take_user=false +take_host=false +take_accept_header=false +take_contenttype_header=false + +for key in "$@"; do +# Take the value of -u|--user argument +if [[ "$take_user" = true ]]; then + basic_auth_credential="$key" + take_user=false + continue +fi +# Take the value of --host argument +if [[ "$take_host" = true ]]; then + host="$key" + take_host=false + continue +fi +# Take the value of --accept argument +if [[ "$take_accept_header" = true ]]; then + header_accept=$(lookup_mime_type "$key") + take_accept_header=false + continue +fi +# Take the value of --content-type argument +if [[ "$take_contenttype_header" = true ]]; then + header_content_type=$(lookup_mime_type "$key") + take_contenttype_header=false + continue +fi +case $key in + -h|--help) + if [[ "x$operation" == "x" ]]; then + print_help + exit 0 + else + eval "print_${operation}_help" + exit 0 + fi + ;; + -V|--version) + print_version + exit 0 + ;; + --about) + print_about + exit 0 + ;; + -u|--user) + take_user=true + ;; + --host) + take_host=true + ;; + --force) + force=true + ;; + -ac|--accept) + take_accept_header=true + ;; + -ct|--content-type) + take_contenttype_header=true + ;; + --dry-run) + print_curl=true + ;; +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + operation="{{operationId}}" + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + *==*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content as strings + if [[ "$operation" ]]; then + IFS='==' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]="\"${body_value}\"" + fi + ;; + *:=*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content without qoutes + if [[ "$operation" ]]; then + IFS=':=' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]=${body_value} + fi + ;; + *:*) + # Parse header arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS=':' read header_name header_value <<< "$key" +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + # + # If the header key is the same as the api_key expected by API in the + # header, override the ${apikey_auth_credential} variable + # + if [[ $header_name == "{{keyParamName}}" ]]; then + apikey_auth_credential=$header_value + fi +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + header_arguments[$header_name]=$header_value + else + curl_arguments+=" $key" + fi + ;; + -) + body_content_temp_file=$(mktemp) + cat - > $body_content_temp_file + ;; + *=*) + # Parse operation arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS='=' read parameter_name parameter_value <<< "$key" + if [[ -z "${operation_parameters[$parameter_name]+foo}" ]]; then + operation_parameters[$parameter_name]=$(url_escape "${parameter_value}") + else + operation_parameters[$parameter_name]+=":::"$(url_escape "${parameter_value}") + fi + else + curl_arguments+=" $key" + fi + ;; + *) + # If we are before the operation, treat the arguments as cURL arguments + if [[ "x$operation" == "x" ]]; then + # Maintain quotes around cURL arguments if necessary + space_regexp="[[:space:]]" + if [[ $key =~ $space_regexp ]]; then + curl_arguments+=" \"$key\"" + else + curl_arguments+=" $key" + fi + fi + ;; +esac +done + + +# Check if user provided host name +if [[ -z "$host" ]]; then + echo "Error: No hostname provided!!!" + echo "Check usage: '${script_name} --help'" + exit 1 +fi + +# Check if user specified operation ID +if [[ -z "$operation" ]]; then + echo "Error: No operation specified!" + echo "Check available operations: '${script_name} --help'" + exit 1 +fi + + +# Run cURL command based on the operation ID +case $operation in +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + call_{{operationId}} + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + *) + echo "Error: Unknown operation: $operation" + echo "" + print_help + exit 1 +esac + diff --git a/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache new file mode 100644 index 00000000000..78caea2bc21 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache @@ -0,0 +1,301 @@ +#compdef {{scriptName}} + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! +# ! Generated on: {{generatedDate}} +# ! +# ! +# ! Installation: +# ! +# ! Copy the _{{scriptName}} file to any directory under FPATH +# ! environment variable (echo $FPATH) +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +# +# cURL crypto engines completion function +# +_curl_crypto_engine() { + local vals + vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} ) + _describe -t outputs 'engines' vals && return 0 +} + +# +# cURL post data completion functions= +# +_curl_post_data() { + + # don't do anything further if this is raw content + compset -P '=' && _message 'raw content' && return 0 + + # complete filename or stdin for @ syntax + compset -P '*@' && { + local expl + _description files expl stdin + compadd "$expl[@]" - "-" + _files + return 0 + } + + # got a name already? expecting data. + compset -P '*=' && _message 'data value' && return 0 + + # otherwise, name (or @ or =) should be specified + _message 'data name' && return 0 + +} + + +local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output + +# HTTP Arguments +arg_http=(''\ + {-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \ + {-b,--cookie}'[pass data to http server as cookie]:data or file' \ + {-c,--cookie-jar}'[specify cookie file]:file name:_files' \ + {-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \ + '--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \ + '--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \ + {-f,--fail}'[enable failfast behavior for server errors]' \ + '*'{-F,--form}'[add POST form data]:name=content' \ + {-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \ + '*'{-H,--header}'[specify an extra header]:header' \ + '--ignore-content-length[ignore Content-Length header]' \ + {-i,--include}'[include HTTP header in the output]' \ + {-j,--junk-session-cookies}'[discard all session cookies]' \ + {-e,--referer}'[send url as referer]:referer url:_urls' \ + {-L,--location}'[follow Location headers on http 3XX response]' \ + '--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \ + '--max-redirs[set maximum number of redirection followings allowed]:number' \ + {-J,--remote-header-name}'[use Content-Disposition for output file name]' \ + {-O,--remote-name}'[write to filename parsed from url instead of stdout]' \ + '--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \ + '--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \ + ) + +# FTP arguments +arg_ftp=(\ + {-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \ + '--crlf[convert LF to CRLF in upload]' \ + '--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \ + '--disable-epsv[disable use of EPSV for passive FTP transfers]' \ + '--ftp-account[account data (FTP)]:data' \ + '--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \ + '--ftp-create-dirs[create paths remotely if it does not exist]' \ + '--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \ + '--ftp-pasv[use passive mode for the data connection (FTP)]' \ + '--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \ + '--form-string[like --form, but do not parse content]:name=string' \ + '--ftp-pret[send PRET before PASV]' \ + '--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \ + '--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \ + '--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \ + {-l,--list-only}'[list names only when listing directories (FTP)]' \ + {-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \ + '*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \ + ) + +# Other Protocol arguments +arg_other=(\ + '--mail-from[specify From: address]:address' \ + '--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \ + {-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \ + '--tftp-blksize[set tftp BLKSIZE option]:value' \ + ) + +# Proxy arguments +arg_proxy=(\ + '--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \ + {-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \ + {-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \ + '--proxy-anyauth[use any authentication method for proxy, default to most secure]' \ + '--proxy-basic[use HTTP Basic authentication for proxy]' \ + '--proxy-digest[use http digest authentication for proxy]' \ + '--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \ + '--proxy-ntlm[enable ntlm authentication for proxy]' \ + '--proxy1.0[use http 1.0 proxy]:proxy url' \ + {-x,--proxy}'[use specified proxy]:proxy url' \ + '--socks5-gssapi-service[change service name for socks server]:servicename' \ + '--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \ + ) + +# Crypto arguments +arg_crypto=(\ + {-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \ + {-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \ + {-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \ + '--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \ + '--crlfile[specify file with revoked certificates]:file' \ + '--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \ + {-E,--cert}'[use specified client certificate]:certificate file:_files' \ + '--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \ + '--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \ + '--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \ + '--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \ + '--capath[specify a search path for certificate files]:CA certificate directory:_directories' \ + '--hostpubmd5[check remote hosts public key]:md5 hash' \ + {-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \ + '--key[ssl/ssh private key file name]:key file:_files' \ + '--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \ + '--pubkey[ssh public key file]:pubkey file:_files' \ + '--random-file[set source of random data for ssl]:random source:_files' \ + '--no-sessionid[disable caching of ssl session ids]' \ + '--pass:phrase[passphrase for ssl/ssh private key]' \ + '--ssl[try to use ssl/tls for connection, if available]' \ + '--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \ + '--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \ + '--tlsuser[set username for TLS authentication]:user' \ + '--tlspassword[set password for TLS authentication]:password' \ + ) + +# Connection arguments +arg_connection=(\ + {-4,--ipv4}'[prefer ipv4]' \ + {-6,--ipv6}'[prefer ipv6, if available]' \ + {-B,--use-ascii}'[use ascii mode]' \ + '--compressed[request a compressed transfer]' \ + '--connect-timeout[timeout for connection phase]:seconds' \ + {-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \ + '--interface[work on a specific interface]:name' \ + '--keepalive-time[set time to wait before sending keepalive probes]:seconds' \ + '--limit-rate[specify maximum transfer rate]:speed' \ + '--local-port[set preferred number or range of local ports to use]:num' \ + {-N,--no-buffer}'[disable buffering of the output stream]' \ + '--no-keepalive[disable use of keepalive messages in TCP connections]' \ + '--raw[disable all http decoding and pass raw data]' \ + '--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \ + '--retry[specify maximum number of retries for transient errors]:num' \ + '--retry-delay[specify delay between retries]:seconds' \ + '--retry-max-time[maximum time to spend on retries]:seconds' \ + '--tcp-nodelay[turn on TCP_NODELAY option]' \ + {-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \ + {-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \ + ) + +# Authentication arguments +arg_auth=(\ + '--anyauth[use any authentication method, default to most secure]' \ + '--basic[use HTTP Basic authentication]' \ + '--ntlm[enable ntlm authentication]' \ + '--digest[use http digest authentication]' \ + '--krb[use kerberos authentication]:auth:(clear safe confidential private)' \ + '--negotiate[enable GSS-Negotiate authentication]' \ + {-n,--netrc}'[scan ~/.netrc for login data]' \ + '--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \ + '--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \ + '--tr-encoding[request compressed transfer-encoding]' \ + {-u,--user}'[specify user name and password for server authentication]:user\:password' \ + ) + +# Input arguments +arg_input=(\ + {-C,--continue-at}'[resume at offset ]:offset' \ + {-g,--globoff}'[do not glob {}\[\] letters]' \ + '--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \ + '--proto[specify allowed protocols for transfer]:protocols' \ + '--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \ + {-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + {-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \ + '--url[specify a URL to fetch (multi)]:url:_urls' \ + {-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \ + ) + +# Output arguments +arg_output=(\ + '--create-dirs[create local directory hierarchy as needed]' \ + {-D,--dump-header}'[write protocol headers to file]:dump file:_files' \ + {-o,--output}'[write to specified file instead of stdout]:output file:_files' \ + {--progress-bar,-\#}'[display progress as a simple progress bar]' \ + {-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + '--raw[disable all http decoding and pass raw data]' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \ + '--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \ + '--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \ + {-v,--verbose}'[output debug info]' \ + {-w,--write-out}'[specify message to output on successful operation]:format string' \ + '--xattr[store some file metadata in extended file attributes]' \ + {-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \ + ) + +_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ + {-M,--manual}'[print manual]' \ + '*'{-K,--config}'[use other config file to read arguments from]:config file:_files' \ + '--libcurl[output libcurl code for the operation to file]:output file:_files' \ + {-m,--max-time}'[limit total time of operation]:seconds' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '-q[do not read settings from .curlrc (must be first option)]' \ + {-h,--help}'[Print help and list of operations]' \ + {-V,--version}'[Print service API version]' \ + '--about[Print the information about service]' \ + '--host[Specify the host URL]':URL:_urls \ + '--dry-run[Print out the cURL command without executing it]' \ + {-ac,--accept}'[Set the 'Accept' header in the request]' \ + {-ct,--content-type}'[Set the 'Content-type' header in request]' \ + '1: :->ops' \ + '*:: :->args' \ + && ret=0 + + +case $state in + ops) + # Operations + _values "Operations" \ +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + "{{operationId}}[{{{summary}}}]" {{#hasMore}}\ +{{/hasMore}}{{/operation}}{{/operations}}{{/apis}}{{#hasMore}}\ +{{/hasMore}} +{{/apiInfo}} + + _arguments "(--help)--help[Print information about operation]" + + ret=0 + ;; + args) + case $line[1] in +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + local -a _op_arguments + _op_arguments=( + {{#pathParams}}"{{baseName}}=:{{{description}}}" +{{/pathParams}} {{#queryParams}}{{#isBoolean}}"{{baseName}}=true:{{description}}" + "{{baseName}}=false:{{description}}"{{/isBoolean}}{{^isBoolean}}"{{baseName}}=:{{description}}"{{/isBoolean}} +{{/queryParams}} {{#headerParams}}"{{baseName}}\::{{{description}}}" +{{/headerParams}}) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + esac + ;; + +esac + +return ret \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java new file mode 100644 index 00000000000..9a99726dace --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java @@ -0,0 +1,56 @@ +package io.swagger.codegen.bash; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.BashClientCodegen; +import io.swagger.codegen.options.BashClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class BashClientOptionsTest extends AbstractOptionsTest { + + @Tested + private BashClientCodegen clientCodegen; + + public BashClientOptionsTest() { + super(new BashClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setCurlOptions( + BashClientOptionsProvider.CURL_OPTIONS); + times = 1; + clientCodegen.setProcessMarkdown( + Boolean.parseBoolean( + BashClientOptionsProvider.PROCESS_MARKDOWN)); + times = 1; + clientCodegen.setScriptName( + BashClientOptionsProvider.SCRIPT_NAME); + times = 1; + clientCodegen.setGenerateBashCompletion( + Boolean.parseBoolean( + BashClientOptionsProvider.GENERATE_BASH_COMPLETION)); + times = 1; + clientCodegen.setGenerateZshCompletion( + Boolean.parseBoolean( + BashClientOptionsProvider.GENERATE_ZSH_COMPLETION)); + times = 1; + clientCodegen.setHostEnvironmentVariable( + BashClientOptionsProvider.HOST_ENVIRONMENT_VARIABLE_NAME); + times = 1; + clientCodegen.setApiKeyAuthEnvironmentVariable( + BashClientOptionsProvider.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME); + times = 1; + }}; + } +} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java new file mode 100644 index 00000000000..a59b083201a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java @@ -0,0 +1,158 @@ +package io.swagger.codegen.python; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.BashClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.parser.SwaggerParser; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.testng.annotations.ITestAnnotation; + +import com.google.common.collect.Sets; +import java.util.Map; + +@SuppressWarnings("static-method") +public class BashTest { + + @Test(description = "test basic petstore operation with Bash extensions") + public void petstoreOperationTest() { + + final Swagger swagger + = new SwaggerParser() + .read("src/test/resources/2_0/petstore-bash.json"); + final DefaultCodegen codegen = new BashClientCodegen(); + final Operation findPetsByStatusOperation + = swagger.getPath("/pet/findByStatus").getGet(); + + final CodegenOperation op + = codegen.fromOperation( + "/pet/findByStatus", + "GET", + findPetsByStatusOperation, + swagger.getDefinitions(), + swagger); + + Assert.assertTrue( + op.vendorExtensions.containsKey("x-bash-codegen-sample")); + + Assert.assertEquals( + op.vendorExtensions.get("x-bash-codegen-description"), + "Multiple status 'values' can be provided with comma separated strings"); + + } + + @Test(description = "test basic petstore operation with example body") + public void petstoreParameterExampleTest() { + + final Swagger swagger + = new SwaggerParser() + .read("src/test/resources/2_0/petstore-bash.json"); + final DefaultCodegen codegen = new BashClientCodegen(); + final Operation addPetOperation + = swagger.getPath("/pet").getPost(); + + final CodegenOperation op + = codegen.fromOperation( + "/pet", + "POST", + addPetOperation, + swagger.getDefinitions(), + swagger); + + Assert.assertEquals(op.bodyParams.size(), 1); + + CodegenParameter pet = op.bodyParams.get(0); + + Assert.assertTrue(pet.vendorExtensions + .containsKey("x-codegen-body-example")); + + } + + + @Test(description = "test Bash client codegen escapeText method") + public void escapeTextTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + + Assert.assertEquals(codegen.escapeText("\\/"), "/"); + + Assert.assertEquals(codegen.escapeText("\\"), "\\\\"); + + + ((BashClientCodegen)codegen).setProcessMarkdown(false); + + Assert.assertEquals(codegen.escapeText("__Bold text__"), + "__Bold text__"); + + Assert.assertEquals(codegen.escapeText("**Bold text**"), + "**Bold text**"); + + Assert.assertEquals(codegen.escapeText("*Italic text*"), + "*Italic text*"); + + Assert.assertEquals(codegen.escapeText("_Italic text_"), + "_Italic text_"); + + + ((BashClientCodegen)codegen).setProcessMarkdown(true); + + Assert.assertEquals(codegen.escapeText("__Bold text__"), + "$(tput bold) Bold text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("**Bold text**"), + "$(tput bold) Bold text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("*Italic text*"), + "$(tput dim) Italic text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("_Italic text_"), + "$(tput dim) Italic text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("# SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("## SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("### SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText( + "```\nnice -n 100 mvn test\n```"), + "\n---\nnice -n 100 mvn test\n---"); + } + + @Test(description = "test Bash client codegen escapeUnsafeCharacters method") + public void escapeUnsafeCharactersTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + Assert.assertEquals(codegen.escapeUnsafeCharacters("`no backticks`"), + "'no backticks'"); + + + } + + @Test(description = "test Bash client codegen escapeReservedWord method") + public void escapeReservedWordTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + Assert.assertEquals(codegen.escapeReservedWord("case"), "_case"); + } + + +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java new file mode 100644 index 00000000000..3f3ad19fc1f --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java @@ -0,0 +1,61 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.BashClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class BashClientOptionsProvider implements OptionsProvider { + + public static final String CURL_OPTIONS = "-k --tlsv1.2"; + public static final String PROCESS_MARKDOWN = "true"; + public static final String SCRIPT_NAME = "petstore-cli"; + public static final String GENERATE_BASH_COMPLETION = "true"; + public static final String GENERATE_ZSH_COMPLETION = "false"; + public static final String HOST_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_HOSTNAME"; + public static final String BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_BASIC_AUTH"; + public static final String APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_APIKEY"; + + @Override + public String getLanguage() { + return "bash"; + } + + @Override + public Map createOptions() { + + ImmutableMap.Builder builder + = new ImmutableMap.Builder(); + + return builder + .put(BashClientCodegen.CURL_OPTIONS, CURL_OPTIONS) + .put(BashClientCodegen.SCRIPT_NAME, SCRIPT_NAME) + .put(BashClientCodegen.PROCESS_MARKDOWN, PROCESS_MARKDOWN) + .put(BashClientCodegen.GENERATE_BASH_COMPLETION, + GENERATE_BASH_COMPLETION) + .put(BashClientCodegen.GENERATE_ZSH_COMPLETION, + GENERATE_ZSH_COMPLETION) + .put(BashClientCodegen.HOST_ENVIRONMENT_VARIABLE_NAME, + HOST_ENVIRONMENT_VARIABLE_NAME) + .put(BashClientCodegen.BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME) + .put(BashClientCodegen.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") + .build(); + + } + + @Override + public boolean isServer() { + + return false; + + } +} diff --git a/modules/swagger-codegen/src/test/resources/2_0/bash-config.json b/modules/swagger-codegen/src/test/resources/2_0/bash-config.json new file mode 100644 index 00000000000..a95e6b41733 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/bash-config.json @@ -0,0 +1,10 @@ +{ + "processMarkdown": true, + "curlOptions": "-sS --tlsv1.2", + "scriptName": "petstore-cli", + "generateBashCompletion": true, + "generateZshCompletion": true, + "hostEnvironmentVariable": "PETSTORE_HOST", + "basicAuthEnvironmentVariable": "PETSTORE_BASIC_AUTH", + "apiKeyAuthEnvironmentVariable": "PETSTORE_API_KEY" +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json b/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json new file mode 100644 index 00000000000..b58cd694d4e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json @@ -0,0 +1,1056 @@ +{ + "swagger":"2.0", + "info":{ + "description":"This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version":"1.0.0", + "title":"Swagger Petstore", + "termsOfService":"http://swagger.io/terms/", + "contact":{ + "email":"apiteam@swagger.io" + }, + "license":{ + "name":"Apache 2.0", + "url":"http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host":"petstore.swagger.io", + "basePath":"/v2", + "tags":[ + { + "name":"pet", + "description":"Everything about your Pets", + "externalDocs":{ + "description":"Find out more", + "url":"http://swagger.io" + } + }, + { + "name":"store", + "description":"Access to Petstore orders" + }, + { + "name":"user", + "description":"Operations about user", + "externalDocs":{ + "description":"Find out more about our store", + "url":"http://swagger.io" + } + } + ], + "schemes":[ + "http" + ], + "paths":{ + "/pet":{ + "post":{ + "tags":[ + "pet" + ], + "summary":"Add a new pet to the store", + "description":"", + "operationId":"addPet", + "consumes":[ + "application/json", + "application/xml" + ], + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"Pet object that needs to be added to the store", + "required":true, + "schema":{ + "$ref":"#/definitions/Pet" + } + } + ], + "responses":{ + "405":{ + "description":"Invalid input" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + }, + "put":{ + "tags":[ + "pet" + ], + "summary":"Update an existing pet", + "description":"", + "operationId":"updatePet", + "consumes":[ + "application/json", + "application/xml" + ], + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"Pet object that needs to be added to the store", + "required":true, + "schema":{ + "$ref":"#/definitions/Pet" + } + } + ], + "responses":{ + "400":{ + "description":"Invalid ID supplied" + }, + "404":{ + "description":"Pet not found" + }, + "405":{ + "description":"Validation exception" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus":{ + "get":{ + "tags":[ + "pet" + ], + "summary":"Finds Pets by status", + "x-bash-codegen-description": "Multiple status `values` can be provided with comma separated strings", + "description": "Multiple status values can be provided with comma separated strings", + "operationId":"findPetsByStatus", + "produces":[ + "application/xml", + "application/json" + ], + "x-code-samples":[ + { + "lang": "Shell", + "source": "petstore-cli findPetsByStatus status=available" + } + ], + "parameters":[ + { + "name":"status", + "in":"query", + "description":"Status values that need to be considered for filter", + "required":true, + "type":"array", + "items":{ + "type":"string", + "enum":[ + "available", + "pending", + "sold" + ], + "default":"available" + }, + "collectionFormat":"multi" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "type":"array", + "items":{ + "$ref":"#/definitions/Pet" + } + } + }, + "400":{ + "description":"Invalid status value" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags":{ + "get":{ + "tags":[ + "pet" + ], + "summary":"Finds Pets by tags", + "description":"Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId":"findPetsByTags", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"tags", + "in":"query", + "description":"Tags to filter by", + "required":true, + "type":"array", + "items":{ + "type":"string" + }, + "collectionFormat":"csv" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "type":"array", + "items":{ + "$ref":"#/definitions/Pet" + } + } + }, + "400":{ + "description":"Invalid tag value" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ], + "deprecated":true + } + }, + "/pet/{petId}":{ + "get":{ + "tags":[ + "pet" + ], + "summary":"Find pet by ID", + "description":"Returns a single pet", + "operationId":"getPetById", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"petId", + "in":"path", + "description":"ID of pet to return", + "required":true, + "type":"integer", + "format":"int64" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "$ref":"#/definitions/Pet" + } + }, + "400":{ + "description":"Invalid ID supplied" + }, + "404":{ + "description":"Pet not found" + } + }, + "security":[ + { + "api_key":[ + + ] + } + ] + }, + "post":{ + "tags":[ + "pet" + ], + "summary":"Updates a pet in the store with form data", + "description":"", + "operationId":"updatePetWithForm", + "consumes":[ + "application/x-www-form-urlencoded" + ], + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"petId", + "in":"path", + "description":"ID of pet that needs to be updated", + "required":true, + "type":"integer", + "format":"int64" + }, + { + "name":"name", + "in":"formData", + "description":"Updated name of the pet", + "required":false, + "type":"string" + }, + { + "name":"status", + "in":"formData", + "description":"Updated status of the pet", + "required":false, + "type":"string" + } + ], + "responses":{ + "405":{ + "description":"Invalid input" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete":{ + "tags":[ + "pet" + ], + "summary":"Deletes a pet", + "description":"", + "operationId":"deletePet", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"api_key", + "in":"header", + "required":false, + "type":"string" + }, + { + "name":"petId", + "in":"path", + "description":"Pet id to delete", + "required":true, + "type":"integer", + "format":"int64" + } + ], + "responses":{ + "400":{ + "description":"Invalid ID supplied" + }, + "404":{ + "description":"Pet not found" + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage":{ + "post":{ + "tags":[ + "pet" + ], + "summary":"uploads an image", + "description":"", + "operationId":"uploadFile", + "consumes":[ + "multipart/form-data" + ], + "produces":[ + "application/json" + ], + "parameters":[ + { + "name":"petId", + "in":"path", + "description":"ID of pet to update", + "required":true, + "type":"integer", + "format":"int64" + }, + { + "name":"additionalMetadata", + "in":"formData", + "description":"Additional data to pass to server", + "required":false, + "type":"string" + }, + { + "name":"file", + "in":"formData", + "description":"file to upload", + "required":false, + "type":"file" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "$ref":"#/definitions/ApiResponse" + } + } + }, + "security":[ + { + "petstore_auth":[ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory":{ + "get":{ + "tags":[ + "store" + ], + "summary":"Returns pet inventories by status", + "description":"Returns a map of status codes to quantities", + "operationId":"getInventory", + "produces":[ + "application/json" + ], + "parameters":[ + + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "type":"object", + "additionalProperties":{ + "type":"integer", + "format":"int32" + } + } + } + }, + "security":[ + { + "api_key":[ + + ] + } + ] + } + }, + "/store/order":{ + "post":{ + "tags":[ + "store" + ], + "summary":"Place an order for a pet", + "description":"", + "operationId":"placeOrder", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"order placed for purchasing the pet", + "required":true, + "schema":{ + "$ref":"#/definitions/Order" + } + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "$ref":"#/definitions/Order" + } + }, + "400":{ + "description":"Invalid Order" + } + } + } + }, + "/store/order/{orderId}":{ + "get":{ + "tags":[ + "store" + ], + "summary":"Find purchase order by ID", + "description":"For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId":"getOrderById", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"orderId", + "in":"path", + "description":"ID of pet that needs to be fetched", + "required":true, + "type":"integer", + "maximum":10.0, + "minimum":1.0, + "format":"int64" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "$ref":"#/definitions/Order" + } + }, + "400":{ + "description":"Invalid ID supplied" + }, + "404":{ + "description":"Order not found" + } + } + }, + "delete":{ + "tags":[ + "store" + ], + "summary":"Delete purchase order by ID", + "description":"For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId":"deleteOrder", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"orderId", + "in":"path", + "description":"ID of the order that needs to be deleted", + "required":true, + "type":"integer", + "minimum":1.0, + "format":"int64" + } + ], + "responses":{ + "400":{ + "description":"Invalid ID supplied" + }, + "404":{ + "description":"Order not found" + } + } + } + }, + "/user":{ + "post":{ + "tags":[ + "user" + ], + "summary":"Create user", + "description":"This can only be done by the logged in user.", + "operationId":"createUser", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"Created user object", + "required":true, + "schema":{ + "$ref":"#/definitions/User" + } + } + ], + "responses":{ + "default":{ + "description":"successful operation" + } + } + } + }, + "/user/createWithArray":{ + "post":{ + "tags":[ + "user" + ], + "summary":"Creates list of users with given input array", + "description":"", + "operationId":"createUsersWithArrayInput", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"List of user object", + "required":true, + "schema":{ + "type":"array", + "items":{ + "$ref":"#/definitions/User" + } + } + } + ], + "responses":{ + "default":{ + "description":"successful operation" + } + } + } + }, + "/user/createWithList":{ + "post":{ + "tags":[ + "user" + ], + "summary":"Creates list of users with given input array", + "description":"", + "operationId":"createUsersWithListInput", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "in":"body", + "name":"body", + "description":"List of user object", + "required":true, + "schema":{ + "type":"array", + "items":{ + "$ref":"#/definitions/User" + } + } + } + ], + "responses":{ + "default":{ + "description":"successful operation" + } + } + } + }, + "/user/login":{ + "get":{ + "tags":[ + "user" + ], + "summary":"Logs user into the system", + "description":"", + "operationId":"loginUser", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"username", + "in":"query", + "description":"The user name for login", + "required":true, + "type":"string" + }, + { + "name":"password", + "in":"query", + "description":"The password for login in clear text", + "required":true, + "type":"string" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "type":"string" + }, + "headers":{ + "X-Rate-Limit":{ + "type":"integer", + "format":"int32", + "description":"calls per hour allowed by the user" + }, + "X-Expires-After":{ + "type":"string", + "format":"date-time", + "description":"date in UTC when token expires" + } + } + }, + "400":{ + "description":"Invalid username/password supplied" + } + } + } + }, + "/user/logout":{ + "get":{ + "tags":[ + "user" + ], + "summary":"Logs out current logged in user session", + "description":"", + "operationId":"logoutUser", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + + ], + "responses":{ + "default":{ + "description":"successful operation" + } + } + } + }, + "/user/{username}":{ + "get":{ + "tags":[ + "user" + ], + "summary":"Get user by user name", + "description":"", + "operationId":"getUserByName", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"username", + "in":"path", + "description":"The name that needs to be fetched. Use user1 for testing. ", + "required":true, + "type":"string" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "$ref":"#/definitions/User" + } + }, + "400":{ + "description":"Invalid username supplied" + }, + "404":{ + "description":"User not found" + } + } + }, + "put":{ + "tags":[ + "user" + ], + "summary":"Updated user", + "description":"This can only be done by the logged in user.", + "operationId":"updateUser", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"username", + "in":"path", + "description":"name that need to be updated", + "required":true, + "type":"string" + }, + { + "in":"body", + "name":"body", + "description":"Updated user object", + "required":true, + "schema":{ + "$ref":"#/definitions/User" + } + } + ], + "responses":{ + "400":{ + "description":"Invalid user supplied" + }, + "404":{ + "description":"User not found" + } + } + }, + "delete":{ + "tags":[ + "user" + ], + "summary":"Delete user", + "description":"This can only be done by the logged in user.", + "operationId":"deleteUser", + "produces":[ + "application/xml", + "application/json" + ], + "parameters":[ + { + "name":"username", + "in":"path", + "description":"The name that needs to be deleted", + "required":true, + "type":"string" + } + ], + "responses":{ + "400":{ + "description":"Invalid username supplied" + }, + "404":{ + "description":"User not found" + } + } + } + } + }, + "securityDefinitions":{ + "petstore_auth":{ + "type":"oauth2", + "authorizationUrl":"http://petstore.swagger.io/oauth/dialog", + "flow":"implicit", + "scopes":{ + "write:pets":"modify pets in your account", + "read:pets":"read your pets" + } + }, + "api_key":{ + "type":"apiKey", + "name":"api_key", + "in":"header" + } + }, + "definitions":{ + "Order":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "petId":{ + "type":"integer", + "format":"int64" + }, + "quantity":{ + "type":"integer", + "format":"int32" + }, + "shipDate":{ + "type":"string", + "format":"date-time" + }, + "status":{ + "type":"string", + "description":"Order Status", + "enum":[ + "placed", + "approved", + "delivered" + ] + }, + "complete":{ + "type":"boolean", + "default":false + } + }, + "xml":{ + "name":"Order" + } + }, + "Category":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "name":{ + "type":"string" + } + }, + "xml":{ + "name":"Category" + } + }, + "User":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "username":{ + "type":"string" + }, + "firstName":{ + "type":"string" + }, + "lastName":{ + "type":"string" + }, + "email":{ + "type":"string" + }, + "password":{ + "type":"string" + }, + "phone":{ + "type":"string" + }, + "userStatus":{ + "type":"integer", + "format":"int32", + "description":"User Status" + } + }, + "xml":{ + "name":"User" + } + }, + "Tag":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "name":{ + "type":"string" + } + }, + "xml":{ + "name":"Tag" + } + }, + "Pet":{ + "type":"object", + "required":[ + "name", + "photoUrls" + ], + "example": { + "name": "lucky", + "photoUrls": [ + "http://example.com/lucky1.jpg" + ] + }, + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "category":{ + "$ref":"#/definitions/Category" + }, + "name":{ + "type":"string", + "example":"doggie" + }, + "photoUrls":{ + "type":"array", + "xml":{ + "name":"photoUrl", + "wrapped":true + }, + "items":{ + "type":"string" + } + }, + "tags":{ + "type":"array", + "xml":{ + "name":"tag", + "wrapped":true + }, + "items":{ + "$ref":"#/definitions/Tag" + } + }, + "status":{ + "type":"string", + "description":"pet status in the store", + "enum":[ + "available", + "pending", + "sold" + ] + } + }, + "xml":{ + "name":"Pet" + } + }, + "ApiResponse":{ + "type":"object", + "properties":{ + "code":{ + "type":"integer", + "format":"int32" + }, + "type":{ + "type":"string" + }, + "message":{ + "type":"string" + } + } + } + }, + "externalDocs":{ + "description":"Find out more about Swagger", + "url":"http://swagger.io" + } +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index 43fcd5542d1..063b84da50d 100644 --- a/pom.xml +++ b/pom.xml @@ -314,6 +314,18 @@ samples/client/petstore/android/volley + + bash-client + + + env + java + + + + samples/client/petstore/bash + + clojure-client @@ -748,6 +760,7 @@ samples/client/petstore/ruby samples/client/petstore/android/volley + samples/client/petstore/bash samples/client/petstore/clojure samples/client/petstore/go samples/client/petstore/java/feign diff --git a/samples/client/petstore/bash/.swagger-codegen-ignore b/samples/client/petstore/bash/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/bash/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/bash/README.md b/samples/client/petstore/bash/README.md new file mode 100644 index 00000000000..ba13931cd24 --- /dev/null +++ b/samples/client/petstore/bash/README.md @@ -0,0 +1,75 @@ +# Swagger Petstore Bash client + +## Overview +This is a Bash client script for accessing Swagger Petstore service. + +The script uses cURL underneath for making all REST calls. + +## Usage + +```shell +# Make sure the script has executable rights +$ chmod u+x petstore-cli + +# Print the list of operations available on the service +$ ./petstore-cli -h + +# Print the service description +$ ./petstore-cli --about + +# Print detailed information about specific operation +$ ./petstore-cli -h + +# Make GET request +./petstore-cli --host http://: --accept xml = : + +# Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password +petstore-cli -k -sS --tlsv1.2 --host https:// -u : --accept xml = : + +# Make POST request +$ echo '' | petstore-cli --host --content-type json - + +# Make POST request with simple JSON content, e.g.: +# { +# "key1": "value1", +# "key2": "value2", +# "key3": 23 +# } +$ echo '' | petstore-cli --host --content-type json key1==value1 key2=value2 key3:=23 - + +# Preview the cURL command without actually executing it +$ petstore-cli --host http://: --dry-run + +``` + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source petstore-cli.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_petstore-cli` Zsh completion file must be copied to one of the folders under `$FPATH` variable. + diff --git a/samples/client/petstore/bash/_petstore-cli b/samples/client/petstore/bash/_petstore-cli new file mode 100644 index 00000000000..6ff898e15c6 --- /dev/null +++ b/samples/client/petstore/bash/_petstore-cli @@ -0,0 +1,454 @@ +#compdef petstore-cli + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! +# ! Generated on: 2017-01-12T00:07:27.471+01:00 +# ! +# ! +# ! Installation: +# ! +# ! Copy the _petstore-cli file to any directory under FPATH +# ! environment variable (echo $FPATH) +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +# +# cURL crypto engines completion function +# +_curl_crypto_engine() { + local vals + vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} ) + _describe -t outputs 'engines' vals && return 0 +} + +# +# cURL post data completion functions= +# +_curl_post_data() { + + # don't do anything further if this is raw content + compset -P '=' && _message 'raw content' && return 0 + + # complete filename or stdin for @ syntax + compset -P '*@' && { + local expl + _description files expl stdin + compadd "$expl[@]" - "-" + _files + return 0 + } + + # got a name already? expecting data. + compset -P '*=' && _message 'data value' && return 0 + + # otherwise, name (or @ or =) should be specified + _message 'data name' && return 0 + +} + + +local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output + +# HTTP Arguments +arg_http=(''\ + {-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \ + {-b,--cookie}'[pass data to http server as cookie]:data or file' \ + {-c,--cookie-jar}'[specify cookie file]:file name:_files' \ + {-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \ + '--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \ + '--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \ + {-f,--fail}'[enable failfast behavior for server errors]' \ + '*'{-F,--form}'[add POST form data]:name=content' \ + {-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \ + '*'{-H,--header}'[specify an extra header]:header' \ + '--ignore-content-length[ignore Content-Length header]' \ + {-i,--include}'[include HTTP header in the output]' \ + {-j,--junk-session-cookies}'[discard all session cookies]' \ + {-e,--referer}'[send url as referer]:referer url:_urls' \ + {-L,--location}'[follow Location headers on http 3XX response]' \ + '--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \ + '--max-redirs[set maximum number of redirection followings allowed]:number' \ + {-J,--remote-header-name}'[use Content-Disposition for output file name]' \ + {-O,--remote-name}'[write to filename parsed from url instead of stdout]' \ + '--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \ + '--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \ + ) + +# FTP arguments +arg_ftp=(\ + {-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \ + '--crlf[convert LF to CRLF in upload]' \ + '--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \ + '--disable-epsv[disable use of EPSV for passive FTP transfers]' \ + '--ftp-account[account data (FTP)]:data' \ + '--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \ + '--ftp-create-dirs[create paths remotely if it does not exist]' \ + '--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \ + '--ftp-pasv[use passive mode for the data connection (FTP)]' \ + '--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \ + '--form-string[like --form, but do not parse content]:name=string' \ + '--ftp-pret[send PRET before PASV]' \ + '--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \ + '--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \ + '--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \ + {-l,--list-only}'[list names only when listing directories (FTP)]' \ + {-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \ + '*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \ + ) + +# Other Protocol arguments +arg_other=(\ + '--mail-from[specify From: address]:address' \ + '--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \ + {-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \ + '--tftp-blksize[set tftp BLKSIZE option]:value' \ + ) + +# Proxy arguments +arg_proxy=(\ + '--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \ + {-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \ + {-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \ + '--proxy-anyauth[use any authentication method for proxy, default to most secure]' \ + '--proxy-basic[use HTTP Basic authentication for proxy]' \ + '--proxy-digest[use http digest authentication for proxy]' \ + '--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \ + '--proxy-ntlm[enable ntlm authentication for proxy]' \ + '--proxy1.0[use http 1.0 proxy]:proxy url' \ + {-x,--proxy}'[use specified proxy]:proxy url' \ + '--socks5-gssapi-service[change service name for socks server]:servicename' \ + '--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \ + ) + +# Crypto arguments +arg_crypto=(\ + {-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \ + {-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \ + {-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \ + '--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \ + '--crlfile[specify file with revoked certificates]:file' \ + '--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \ + {-E,--cert}'[use specified client certificate]:certificate file:_files' \ + '--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \ + '--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \ + '--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \ + '--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \ + '--capath[specify a search path for certificate files]:CA certificate directory:_directories' \ + '--hostpubmd5[check remote hosts public key]:md5 hash' \ + {-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \ + '--key[ssl/ssh private key file name]:key file:_files' \ + '--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \ + '--pubkey[ssh public key file]:pubkey file:_files' \ + '--random-file[set source of random data for ssl]:random source:_files' \ + '--no-sessionid[disable caching of ssl session ids]' \ + '--pass:phrase[passphrase for ssl/ssh private key]' \ + '--ssl[try to use ssl/tls for connection, if available]' \ + '--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \ + '--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \ + '--tlsuser[set username for TLS authentication]:user' \ + '--tlspassword[set password for TLS authentication]:password' \ + ) + +# Connection arguments +arg_connection=(\ + {-4,--ipv4}'[prefer ipv4]' \ + {-6,--ipv6}'[prefer ipv6, if available]' \ + {-B,--use-ascii}'[use ascii mode]' \ + '--compressed[request a compressed transfer]' \ + '--connect-timeout[timeout for connection phase]:seconds' \ + {-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \ + '--interface[work on a specific interface]:name' \ + '--keepalive-time[set time to wait before sending keepalive probes]:seconds' \ + '--limit-rate[specify maximum transfer rate]:speed' \ + '--local-port[set preferred number or range of local ports to use]:num' \ + {-N,--no-buffer}'[disable buffering of the output stream]' \ + '--no-keepalive[disable use of keepalive messages in TCP connections]' \ + '--raw[disable all http decoding and pass raw data]' \ + '--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \ + '--retry[specify maximum number of retries for transient errors]:num' \ + '--retry-delay[specify delay between retries]:seconds' \ + '--retry-max-time[maximum time to spend on retries]:seconds' \ + '--tcp-nodelay[turn on TCP_NODELAY option]' \ + {-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \ + {-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \ + ) + +# Authentication arguments +arg_auth=(\ + '--anyauth[use any authentication method, default to most secure]' \ + '--basic[use HTTP Basic authentication]' \ + '--ntlm[enable ntlm authentication]' \ + '--digest[use http digest authentication]' \ + '--krb[use kerberos authentication]:auth:(clear safe confidential private)' \ + '--negotiate[enable GSS-Negotiate authentication]' \ + {-n,--netrc}'[scan ~/.netrc for login data]' \ + '--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \ + '--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \ + '--tr-encoding[request compressed transfer-encoding]' \ + {-u,--user}'[specify user name and password for server authentication]:user\:password' \ + ) + +# Input arguments +arg_input=(\ + {-C,--continue-at}'[resume at offset ]:offset' \ + {-g,--globoff}'[do not glob {}\[\] letters]' \ + '--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \ + '--proto[specify allowed protocols for transfer]:protocols' \ + '--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \ + {-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + {-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \ + '--url[specify a URL to fetch (multi)]:url:_urls' \ + {-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \ + ) + +# Output arguments +arg_output=(\ + '--create-dirs[create local directory hierarchy as needed]' \ + {-D,--dump-header}'[write protocol headers to file]:dump file:_files' \ + {-o,--output}'[write to specified file instead of stdout]:output file:_files' \ + {--progress-bar,-\#}'[display progress as a simple progress bar]' \ + {-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + '--raw[disable all http decoding and pass raw data]' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \ + '--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \ + '--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \ + {-v,--verbose}'[output debug info]' \ + {-w,--write-out}'[specify message to output on successful operation]:format string' \ + '--xattr[store some file metadata in extended file attributes]' \ + {-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \ + ) + +_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ + {-M,--manual}'[print manual]' \ + '*'{-K,--config}'[use other config file to read arguments from]:config file:_files' \ + '--libcurl[output libcurl code for the operation to file]:output file:_files' \ + {-m,--max-time}'[limit total time of operation]:seconds' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '-q[do not read settings from .curlrc (must be first option)]' \ + {-h,--help}'[Print help and list of operations]' \ + {-V,--version}'[Print service API version]' \ + '--about[Print the information about service]' \ + '--host[Specify the host URL]':URL:_urls \ + '--dry-run[Print out the cURL command without executing it]' \ + {-ac,--accept}'[Set the 'Accept' header in the request]' \ + {-ct,--content-type}'[Set the 'Content-type' header in request]' \ + '1: :->ops' \ + '*:: :->args' \ + && ret=0 + + +case $state in + ops) + # Operations + _values "Operations" \ + "testClientModel[To test \"client\" model]" \ + "testEndpointParameters[Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트]" \ + "testEnumParameters[To test enum parameters]" "addPet[Add a new pet to the store]" \ + "deletePet[Deletes a pet]" \ + "findPetsByStatus[Finds Pets by status]" \ + "findPetsByTags[Finds Pets by tags]" \ + "getPetById[Find pet by ID]" \ + "updatePet[Update an existing pet]" \ + "updatePetWithForm[Updates a pet in the store with form data]" \ + "uploadFile[uploads an image]" "deleteOrder[Delete purchase order by ID]" \ + "getInventory[Returns pet inventories by status]" \ + "getOrderById[Find purchase order by ID]" \ + "placeOrder[Place an order for a pet]" "createUser[Create user]" \ + "createUsersWithArrayInput[Creates list of users with given input array]" \ + "createUsersWithListInput[Creates list of users with given input array]" \ + "deleteUser[Delete user]" \ + "getUserByName[Get user by user name]" \ + "loginUser[Logs user into the system]" \ + "logoutUser[Logs out current logged in user session]" \ + "updateUser[Updated user]" + _arguments "(--help)--help[Print information about operation]" + + ret=0 + ;; + args) + case $line[1] in + testClientModel) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + testEndpointParameters) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + testEnumParameters) + local -a _op_arguments + _op_arguments=( + "enum_query_string_array=:Query parameter enum test (string array)" +"enum_query_string=:Query parameter enum test (string)" +"enum_query_integer=:Query parameter enum test (double)" + "enum_header_string_array\::Header parameter enum test (string array)" +"enum_header_string\::Header parameter enum test (string)" +) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + addPet) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + deletePet) + local -a _op_arguments + _op_arguments=( + "petId=:Pet id to delete" + "api_key\::" +) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + findPetsByStatus) + local -a _op_arguments + _op_arguments=( + "status=:Status values that need to be considered for filter" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + findPetsByTags) + local -a _op_arguments + _op_arguments=( + "tags=:Tags to filter by" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + getPetById) + local -a _op_arguments + _op_arguments=( + "petId=:ID of pet to return" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + updatePet) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + updatePetWithForm) + local -a _op_arguments + _op_arguments=( + "petId=:ID of pet that needs to be updated" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + uploadFile) + local -a _op_arguments + _op_arguments=( + "petId=:ID of pet to update" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + deleteOrder) + local -a _op_arguments + _op_arguments=( + "orderId=:ID of the order that needs to be deleted" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + getInventory) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + getOrderById) + local -a _op_arguments + _op_arguments=( + "orderId=:ID of pet that needs to be fetched" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + placeOrder) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + createUser) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + createUsersWithArrayInput) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + createUsersWithListInput) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + deleteUser) + local -a _op_arguments + _op_arguments=( + "username=:The name that needs to be deleted" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + getUserByName) + local -a _op_arguments + _op_arguments=( + "username=:The name that needs to be fetched. Use user1 for testing." + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + loginUser) + local -a _op_arguments + _op_arguments=( + "username=:The user name for login" +"password=:The password for login in clear text" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + logoutUser) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + updateUser) + local -a _op_arguments + _op_arguments=( + "username=:name that need to be deleted" + ) + _describe -t actions 'operations' _op_arguments && ret=0 + ;; + esac + ;; + +esac + +return ret \ No newline at end of file diff --git a/samples/client/petstore/bash/petstore-cli b/samples/client/petstore/bash/petstore-cli new file mode 100755 index 00000000000..cff2a4cf5f8 --- /dev/null +++ b/samples/client/petstore/bash/petstore-cli @@ -0,0 +1,3312 @@ +#!/usr/bin/env bash + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: 2017-01-12T00:07:27.471+01:00 +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# +# This is a Bash client for Swagger Petstore. +# +# LICENSE: +# http://www.apache.org/licenses/LICENSE-2.0.html +# +# CONTACT: +# apiteam@swagger.io +# +# MORE INFORMATION: +# http://swagger.io +# + + +############################################################################### +# +# Global variables +# +############################################################################### + +## +# The filename of this script for help messages +script_name=`basename "$0"` + +## +# Map for headers passed after operation as KEY:VALUE +declare -A header_arguments + + +## +# Map for operation parameters passed after operation as PARAMETER=VALUE +# These will be mapped to appropriate path or query parameters +# The values in operation_parameters are arrays, so that multiple values +# can be provided for the same parameter if allowed by API specification +declare -A operation_parameters + +## +# This array stores the minimum number of required occurences for parameter +# 0 - optional +# 1 - required +declare -A operation_parameters_minimum_occurences +operation_parameters_minimum_occurences["testClientModel:::body"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::number"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::double"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::pattern_without_delimiter"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::byte"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::integer"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::int32"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::int64"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::float"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::string"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::binary"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::date"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::dateTime"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::password"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::callback"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_form_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_form_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_header_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_header_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_integer"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_double"]=0 +operation_parameters_minimum_occurences["addPet:::body"]=1 +operation_parameters_minimum_occurences["deletePet:::petId"]=1 +operation_parameters_minimum_occurences["deletePet:::api_key"]=0 +operation_parameters_minimum_occurences["findPetsByStatus:::status"]=1 +operation_parameters_minimum_occurences["findPetsByTags:::tags"]=1 +operation_parameters_minimum_occurences["getPetById:::petId"]=1 +operation_parameters_minimum_occurences["updatePet:::body"]=1 +operation_parameters_minimum_occurences["updatePetWithForm:::petId"]=1 +operation_parameters_minimum_occurences["updatePetWithForm:::name"]=0 +operation_parameters_minimum_occurences["updatePetWithForm:::status"]=0 +operation_parameters_minimum_occurences["uploadFile:::petId"]=1 +operation_parameters_minimum_occurences["uploadFile:::additionalMetadata"]=0 +operation_parameters_minimum_occurences["uploadFile:::file"]=0 +operation_parameters_minimum_occurences["deleteOrder:::orderId"]=1 +operation_parameters_minimum_occurences["getOrderById:::orderId"]=1 +operation_parameters_minimum_occurences["placeOrder:::body"]=1 +operation_parameters_minimum_occurences["createUser:::body"]=1 +operation_parameters_minimum_occurences["createUsersWithArrayInput:::body"]=1 +operation_parameters_minimum_occurences["createUsersWithListInput:::body"]=1 +operation_parameters_minimum_occurences["deleteUser:::username"]=1 +operation_parameters_minimum_occurences["getUserByName:::username"]=1 +operation_parameters_minimum_occurences["loginUser:::username"]=1 +operation_parameters_minimum_occurences["loginUser:::password"]=1 +operation_parameters_minimum_occurences["updateUser:::username"]=1 +operation_parameters_minimum_occurences["updateUser:::body"]=1 + +## +# This array stores the maximum number of allowed occurences for parameter +# 1 - single value +# 2 - 2 values +# N - N values +# 0 - unlimited +declare -A operation_parameters_maximum_occurences +operation_parameters_maximum_occurences["testClientModel:::body"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::number"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::double"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::pattern_without_delimiter"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::byte"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::integer"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::int32"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::int64"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::float"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::string"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::binary"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::date"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::dateTime"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::password"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::callback"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_form_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_form_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_header_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_header_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_integer"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_double"]=0 +operation_parameters_maximum_occurences["addPet:::body"]=0 +operation_parameters_maximum_occurences["deletePet:::petId"]=0 +operation_parameters_maximum_occurences["deletePet:::api_key"]=0 +operation_parameters_maximum_occurences["findPetsByStatus:::status"]=0 +operation_parameters_maximum_occurences["findPetsByTags:::tags"]=0 +operation_parameters_maximum_occurences["getPetById:::petId"]=0 +operation_parameters_maximum_occurences["updatePet:::body"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::petId"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::name"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::status"]=0 +operation_parameters_maximum_occurences["uploadFile:::petId"]=0 +operation_parameters_maximum_occurences["uploadFile:::additionalMetadata"]=0 +operation_parameters_maximum_occurences["uploadFile:::file"]=0 +operation_parameters_maximum_occurences["deleteOrder:::orderId"]=0 +operation_parameters_maximum_occurences["getOrderById:::orderId"]=0 +operation_parameters_maximum_occurences["placeOrder:::body"]=0 +operation_parameters_maximum_occurences["createUser:::body"]=0 +operation_parameters_maximum_occurences["createUsersWithArrayInput:::body"]=0 +operation_parameters_maximum_occurences["createUsersWithListInput:::body"]=0 +operation_parameters_maximum_occurences["deleteUser:::username"]=0 +operation_parameters_maximum_occurences["getUserByName:::username"]=0 +operation_parameters_maximum_occurences["loginUser:::username"]=0 +operation_parameters_maximum_occurences["loginUser:::password"]=0 +operation_parameters_maximum_occurences["updateUser:::username"]=0 +operation_parameters_maximum_occurences["updateUser:::body"]=0 + +## +# The type of collection for specifying multiple values for parameter: +# - multi, csv, ssv, tsv +declare -A operation_parameters_collection_type +operation_parameters_collection_type["testClientModel:::body"]="" +operation_parameters_collection_type["testEndpointParameters:::number"]="" +operation_parameters_collection_type["testEndpointParameters:::double"]="" +operation_parameters_collection_type["testEndpointParameters:::pattern_without_delimiter"]="" +operation_parameters_collection_type["testEndpointParameters:::byte"]="" +operation_parameters_collection_type["testEndpointParameters:::integer"]="" +operation_parameters_collection_type["testEndpointParameters:::int32"]="" +operation_parameters_collection_type["testEndpointParameters:::int64"]="" +operation_parameters_collection_type["testEndpointParameters:::float"]="" +operation_parameters_collection_type["testEndpointParameters:::string"]="" +operation_parameters_collection_type["testEndpointParameters:::binary"]="" +operation_parameters_collection_type["testEndpointParameters:::date"]="" +operation_parameters_collection_type["testEndpointParameters:::dateTime"]="" +operation_parameters_collection_type["testEndpointParameters:::password"]="" +operation_parameters_collection_type["testEndpointParameters:::callback"]="" +operation_parameters_collection_type["testEnumParameters:::enum_form_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_form_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_header_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_header_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_query_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_integer"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_double"]="" +operation_parameters_collection_type["addPet:::body"]="" +operation_parameters_collection_type["deletePet:::petId"]="" +operation_parameters_collection_type["deletePet:::api_key"]="" +operation_parameters_collection_type["findPetsByStatus:::status"]="csv" +operation_parameters_collection_type["findPetsByTags:::tags"]="csv" +operation_parameters_collection_type["getPetById:::petId"]="" +operation_parameters_collection_type["updatePet:::body"]="" +operation_parameters_collection_type["updatePetWithForm:::petId"]="" +operation_parameters_collection_type["updatePetWithForm:::name"]="" +operation_parameters_collection_type["updatePetWithForm:::status"]="" +operation_parameters_collection_type["uploadFile:::petId"]="" +operation_parameters_collection_type["uploadFile:::additionalMetadata"]="" +operation_parameters_collection_type["uploadFile:::file"]="" +operation_parameters_collection_type["deleteOrder:::orderId"]="" +operation_parameters_collection_type["getOrderById:::orderId"]="" +operation_parameters_collection_type["placeOrder:::body"]="" +operation_parameters_collection_type["createUser:::body"]="" +operation_parameters_collection_type["createUsersWithArrayInput:::body"]= +operation_parameters_collection_type["createUsersWithListInput:::body"]= +operation_parameters_collection_type["deleteUser:::username"]="" +operation_parameters_collection_type["getUserByName:::username"]="" +operation_parameters_collection_type["loginUser:::username"]="" +operation_parameters_collection_type["loginUser:::password"]="" +operation_parameters_collection_type["updateUser:::username"]="" +operation_parameters_collection_type["updateUser:::body"]="" + + +## +# Map for body parameters passed after operation as +# PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE +# These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) +declare -A body_parameters + +## +# These arguments will be directly passed to cURL +curl_arguments="" + +## +# The host for making the request +host="$PETSTORE_HOST" + +## +# The user credentials for basic authentication +basic_auth_credential="$PETSTORE_BASIC_AUTH" + +## +# The user API key +apikey_auth_credential="$PETSTORE_API_KEY" + +## +# If true, the script will only output the actual cURL command that would be +# used +print_curl=false + +## +# The operation ID passed on the command line +operation="" + +## +# The provided Accept header value +header_accept="" + +## +# The provided Content-type header value +header_content_type="" + +## +# If there is any body content on the stdin pass it to the body of the request +body_content_temp_file="" + +## +# If this variable is set to true, the request will be performed even +# if parameters for required query, header or body values are not provided +# (path parameters are still required). +force=false + +## +# Declare some mime types abbreviations for easier content-type and accepts +# headers specification +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +############################################################################## +# +# Escape special URL characters +# Based on table at http://www.w3schools.com/tags/ref_urlencode.asp +# +############################################################################## +url_escape() { + local raw_url="$1" + + value=$(sed -e 's/ /%20/g' \ + -e 's/!/%21/g' \ + -e 's/"/%22/g' \ + -e 's/#/%23/g' \ + -e 's/\&/%26/g' \ + -e 's/'\''/%28/g' \ + -e 's/(/%28/g' \ + -e 's/)/%29/g' \ + -e 's/:/%3A/g' \ + -e 's/?/%3F/g' <<<$raw_url); + + echo $value +} + +############################################################################## +# +# Lookup the mime type abbreviation in the mime_type_abbreviations array. +# If not present assume the user provided a valid mime type +# +############################################################################## +lookup_mime_type() { + local mime_type=$1 + + if [[ ${mime_type_abbreviations[$mime_type]} ]]; then + echo ${mime_type_abbreviations[$mime_type]} + else + echo $1 + fi +} + +############################################################################## +# +# Converts an associative array into a list of cURL header +# arguments (-H "KEY: VALUE") +# +############################################################################## +header_arguments_to_curl() { + local headers_curl="" + local api_key_header="" + local api_key_header_in_cli="" + api_key_header="api_key" + + for key in "${!header_arguments[@]}"; do + headers_curl+="-H \"${key}: ${header_arguments[${key}]}\" " + if [[ "${key}XX" == "${api_key_header}XX" ]]; then + api_key_header_in_cli="YES" + fi + done + # + # If the api_key was not provided in the header, try one from the + # environment variable + # + if [[ -z $api_key_header_in_cli && -n $apikey_auth_credential ]]; then + headers_curl+="-H \"${api_key_header}: ${apikey_auth_credential}\"" + fi + headers_curl+=" " + + echo "${headers_curl}" +} + +############################################################################## +# +# Converts an associative array into a simple JSON with keys as top +# level object attributes +# +# \todo Add convertion of more complex attributes using paths +# +############################################################################## +body_parameters_to_json() { + local body_json="-d '{" + local body_parameter_count=${#body_parameters[@]} + local count=0 + for key in "${!body_parameters[@]}"; do + body_json+="\"${key}\": ${body_parameters[${key}]}" + if [[ $count -lt $body_parameter_count-1 ]]; then + body_json+=", " + fi + count+=1 + done + body_json+="}'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_json}" + fi +} + +############################################################################## +# +# Check if provided parameters match specification requirements +# +############################################################################## +validate_request_parameters() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + # Now append query parameters - if any + if [[ ${#query_params[@]} -gt 0 ]]; then + path_template+="?" + fi + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + if [[ "${operation_parameters_collection_type[${operation}:::${qparam}]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + path_template+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="," + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+=" " + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="\t" + fi + vcount+=1 + done + else + echo -e "" + echo -e "Error: Unsupported collection format " + echo -e "" + exit 1 + fi + + + if [[ $count -lt $query_parameter_count-1 ]]; then + path_template+="&" + fi + count+=1 + done + +} + + + +############################################################################## +# +# Build request path including query parameters +# +############################################################################## +build_request_path() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + local query_request_part="" + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + local parameter_value="" + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + # + # Append parameters without specific cardinality + # + if [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'mutli' collections i.e. param=value1¶m=value2&... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'csv' collections i.e. param=value1,value2,... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="," + fi + vcount+=1 + done + # + # Append parameters specified as 'ssv' collections i.e. param="value1 value2 ..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+=" " + fi + vcount+=1 + done + # + # Append parameters specified as 'tsv' collections i.e. param="value1\tvalue2\t..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="\t" + fi + vcount+=1 + done + fi + + if [[ -n "${parameter_value}" ]]; then + query_request_part+="${parameter_value}" + fi + + if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then + query_request_part+="&" + fi + + count+=1 + + done + + + # Now append query parameters - if any + if [[ -n "${query_request_part}" ]]; then + path_template+="?$(echo ${query_request_part} | sed s'/&$//')" + fi + + echo $path_template +} + + + +############################################################################### +# +# Print main help message +# +############################################################################### +print_help() { +cat <$(tput sgr0)] + [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] + + - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath + Can also be specified in PETSTORE_HOST environment variable. + - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + forms: + * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' + +EOF + echo -e "$(tput bold)$(tput setaf 7)Authentication methods$(tput sgr0)" + echo -e "" + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1)api_key:$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_API_KEY=''$(tput sgr0)" + echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_BASIC_AUTH=':'$(tput sgr0)" + echo -e " - $(tput setaf 5)OAuth2 (flow: implicit)$(tput sgr0)" + echo -e " Authorization URL: " + echo -e " * http://petstore.swagger.io/api/oauth/dialog" + echo -e " Scopes:" + echo -e " * write:pets - modify pets in your account" + echo -e " * read:pets - read your pets" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Operations (grouped by tags)$(tput sgr0)" + echo "" + echo -e "$(tput bold)$(tput setaf 7)[fake]$(tput sgr0)" +read -d '' ops <$(tput sgr0)\t\t\t\tSpecify the host URL " +echo -e " \t\t\t\t(e.g. 'https://petstore.swagger.io')" + + echo -e " --force\t\t\t\tForce command invocation in spite of missing" + echo -e " \t\t\t\trequired parameters or wrong content type" + echo -e " --dry-run\t\t\t\tPrint out the cURL command without" + echo -e " \t\t\t\texecuting it" + echo -e " -ac,--accept $(tput setaf 3)$(tput sgr0)\t\tSet the 'Accept' header in the request" + echo -e " -ct,--content-type $(tput setaf 3)$(tput sgr0)\tSet the 'Content-type' header in " + echo -e " \tthe request" + echo "" +} + + +############################################################################## +# +# Print REST service description +# +############################################################################## +print_about() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)Swagger Petstore command line client (API version 1.0.0)$(tput sgr0)" + echo "" + echo -e "License: Apache 2.0" + echo -e "Contact: apiteam@swagger.io" + echo "" +read -d '' appdescription < 10. Other values will generated exceptions" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)orderId$(tput sgr0) $(tput setaf 4)[Integer]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - ID of pet that needs to be fetched $(tput setaf 3)Specify as: orderId=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for placeOrder operation +# +############################################################################## +print_placeOrder_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)placeOrder - Place an order for a pet$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - order placed for purchasing the pet" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUser operation +# +############################################################################## +print_createUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUser - Create user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - Created user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUsersWithArrayInput operation +# +############################################################################## +print_createUsersWithArrayInput_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUsersWithArrayInput - Creates list of users with given input array$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - List of user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUsersWithListInput operation +# +############################################################################## +print_createUsersWithListInput_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUsersWithListInput - Creates list of users with given input array$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - List of user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for deleteUser operation +# +############################################################################## +print_deleteUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)deleteUser - Delete user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The name that needs to be deleted $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for getUserByName operation +# +############################################################################## +print_getUserByName_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)getUserByName - Get user by user name$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The name that needs to be fetched. Use user1 for testing. $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for loginUser operation +# +############################################################################## +print_loginUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)loginUser - Logs user into the system$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The user name for login$(tput setaf 3) Specify as: username=value$(tput sgr0)" \ + | fold -sw 80 | sed '2,$s/^/ /' + echo -e " * $(tput setaf 2)password$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The password for login in clear text$(tput setaf 3) Specify as: password=value$(tput sgr0)" \ + | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + echo -e " $(tput bold)$(tput setaf 7)Response headers$(tput sgr0)" + echo -e " $(tput setaf 4)X-Rate-Limit$(tput sgr0) - calls per hour allowed by the user" | fold -sw 80 | sed '2,$s/^/ /' + echo -e " $(tput setaf 4)X-Expires-After$(tput sgr0) - date in UTC when toekn expires" | fold -sw 80 | sed '2,$s/^/ /' + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for logoutUser operation +# +############################################################################## +print_logoutUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)logoutUser - Logs out current logged in user session$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for updateUser operation +# +############################################################################## +print_updateUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)updateUser - Updated user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - name that need to be deleted $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - Updated user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} + + +############################################################################## +# +# Call testClientModel operation +# +############################################################################## +call_testClientModel() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="PATCH" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + if [[ -z $header_content_type ]]; then + header_content_type="application/json" + fi + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call testEndpointParameters operation +# +############################################################################## +call_testEndpointParameters() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call testEnumParameters operation +# +############################################################################## +call_testEnumParameters() { + local path_parameter_names=() + local query_parameter_names=(enum_query_string_array enum_query_string enum_query_integer) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call addPet operation +# +############################################################################## +call_addPet() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo -e "\t- application/xml" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call deletePet operation +# +############################################################################## +call_deletePet() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call findPetsByStatus operation +# +############################################################################## +call_findPetsByStatus() { + local path_parameter_names=() + local query_parameter_names=(status) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/findByStatus" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/findByStatus" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call findPetsByTags operation +# +############################################################################## +call_findPetsByTags() { + local path_parameter_names=() + local query_parameter_names=(tags) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/findByTags" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/findByTags" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getPetById operation +# +############################################################################## +call_getPetById() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call updatePet operation +# +############################################################################## +call_updatePet() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet" path_parameter_names query_parameter_names) + local method="PUT" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo -e "\t- application/xml" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call updatePetWithForm operation +# +############################################################################## +call_updatePetWithForm() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call uploadFile operation +# +############################################################################## +call_uploadFile() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}/uploadImage" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}/uploadImage" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call deleteOrder operation +# +############################################################################## +call_deleteOrder() { + local path_parameter_names=(orderId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order/{orderId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order/{orderId}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getInventory operation +# +############################################################################## +call_getInventory() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/inventory" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/inventory" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getOrderById operation +# +############################################################################## +call_getOrderById() { + local path_parameter_names=(orderId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order/{orderId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order/{orderId}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call placeOrder operation +# +############################################################################## +call_placeOrder() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUser operation +# +############################################################################## +call_createUser() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUsersWithArrayInput operation +# +############################################################################## +call_createUsersWithArrayInput() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/createWithArray" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/createWithArray" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUsersWithListInput operation +# +############################################################################## +call_createUsersWithListInput() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/createWithList" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/createWithList" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call deleteUser operation +# +############################################################################## +call_deleteUser() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getUserByName operation +# +############################################################################## +call_getUserByName() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call loginUser operation +# +############################################################################## +call_loginUser() { + local path_parameter_names=() + local query_parameter_names=(username password) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/login" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/login" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call logoutUser operation +# +############################################################################## +call_logoutUser() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/logout" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/logout" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call updateUser operation +# +############################################################################## +call_updateUser() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="PUT" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + + + +############################################################################## +# +# Main +# +############################################################################## + + +# Make sure Bash is at least in version 4.3 +if [[ ${BASH_VERSION:0:1} < 4 && ${BASH_VERSION:2:1} < 3 ]]; then + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + exit 1 +fi + +# Check dependencies +type curl >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } +type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } +type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' installed."; exit 1; } + +# +# Process command line +# +# Pass all arguemnts before 'operation' to cURL except the ones we override +# +take_user=false +take_host=false +take_accept_header=false +take_contenttype_header=false + +for key in "$@"; do +# Take the value of -u|--user argument +if [[ "$take_user" = true ]]; then + basic_auth_credential="$key" + take_user=false + continue +fi +# Take the value of --host argument +if [[ "$take_host" = true ]]; then + host="$key" + take_host=false + continue +fi +# Take the value of --accept argument +if [[ "$take_accept_header" = true ]]; then + header_accept=$(lookup_mime_type "$key") + take_accept_header=false + continue +fi +# Take the value of --content-type argument +if [[ "$take_contenttype_header" = true ]]; then + header_content_type=$(lookup_mime_type "$key") + take_contenttype_header=false + continue +fi +case $key in + -h|--help) + if [[ "x$operation" == "x" ]]; then + print_help + exit 0 + else + eval "print_${operation}_help" + exit 0 + fi + ;; + -V|--version) + print_version + exit 0 + ;; + --about) + print_about + exit 0 + ;; + -u|--user) + take_user=true + ;; + --host) + take_host=true + ;; + --force) + force=true + ;; + -ac|--accept) + take_accept_header=true + ;; + -ct|--content-type) + take_contenttype_header=true + ;; + --dry-run) + print_curl=true + ;; + testClientModel) + operation="testClientModel" + ;; + testEndpointParameters) + operation="testEndpointParameters" + ;; + testEnumParameters) + operation="testEnumParameters" + ;; + addPet) + operation="addPet" + ;; + deletePet) + operation="deletePet" + ;; + findPetsByStatus) + operation="findPetsByStatus" + ;; + findPetsByTags) + operation="findPetsByTags" + ;; + getPetById) + operation="getPetById" + ;; + updatePet) + operation="updatePet" + ;; + updatePetWithForm) + operation="updatePetWithForm" + ;; + uploadFile) + operation="uploadFile" + ;; + deleteOrder) + operation="deleteOrder" + ;; + getInventory) + operation="getInventory" + ;; + getOrderById) + operation="getOrderById" + ;; + placeOrder) + operation="placeOrder" + ;; + createUser) + operation="createUser" + ;; + createUsersWithArrayInput) + operation="createUsersWithArrayInput" + ;; + createUsersWithListInput) + operation="createUsersWithListInput" + ;; + deleteUser) + operation="deleteUser" + ;; + getUserByName) + operation="getUserByName" + ;; + loginUser) + operation="loginUser" + ;; + logoutUser) + operation="logoutUser" + ;; + updateUser) + operation="updateUser" + ;; + *==*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content as strings + if [[ "$operation" ]]; then + IFS='==' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]="\"${body_value}\"" + fi + ;; + *:=*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content without qoutes + if [[ "$operation" ]]; then + IFS=':=' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]=${body_value} + fi + ;; + *:*) + # Parse header arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS=':' read header_name header_value <<< "$key" + # + # If the header key is the same as the api_key expected by API in the + # header, override the ${apikey_auth_credential} variable + # + if [[ $header_name == "api_key" ]]; then + apikey_auth_credential=$header_value + fi + header_arguments[$header_name]=$header_value + else + curl_arguments+=" $key" + fi + ;; + -) + body_content_temp_file=$(mktemp) + cat - > $body_content_temp_file + ;; + *=*) + # Parse operation arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS='=' read parameter_name parameter_value <<< "$key" + if [[ -z "${operation_parameters[$parameter_name]+foo}" ]]; then + operation_parameters[$parameter_name]=$(url_escape "${parameter_value}") + else + operation_parameters[$parameter_name]+=":::"$(url_escape "${parameter_value}") + fi + else + curl_arguments+=" $key" + fi + ;; + *) + # If we are before the operation, treat the arguments as cURL arguments + if [[ "x$operation" == "x" ]]; then + # Maintain quotes around cURL arguments if necessary + space_regexp="[[:space:]]" + if [[ $key =~ $space_regexp ]]; then + curl_arguments+=" \"$key\"" + else + curl_arguments+=" $key" + fi + fi + ;; +esac +done + + +# Check if user provided host name +if [[ -z "$host" ]]; then + echo "Error: No hostname provided!!!" + echo "Check usage: '${script_name} --help'" + exit 1 +fi + +# Check if user specified operation ID +if [[ -z "$operation" ]]; then + echo "Error: No operation specified!" + echo "Check available operations: '${script_name} --help'" + exit 1 +fi + + +# Run cURL command based on the operation ID +case $operation in + testClientModel) + call_testClientModel + ;; + testEndpointParameters) + call_testEndpointParameters + ;; + testEnumParameters) + call_testEnumParameters + ;; + addPet) + call_addPet + ;; + deletePet) + call_deletePet + ;; + findPetsByStatus) + call_findPetsByStatus + ;; + findPetsByTags) + call_findPetsByTags + ;; + getPetById) + call_getPetById + ;; + updatePet) + call_updatePet + ;; + updatePetWithForm) + call_updatePetWithForm + ;; + uploadFile) + call_uploadFile + ;; + deleteOrder) + call_deleteOrder + ;; + getInventory) + call_getInventory + ;; + getOrderById) + call_getOrderById + ;; + placeOrder) + call_placeOrder + ;; + createUser) + call_createUser + ;; + createUsersWithArrayInput) + call_createUsersWithArrayInput + ;; + createUsersWithListInput) + call_createUsersWithListInput + ;; + deleteUser) + call_deleteUser + ;; + getUserByName) + call_getUserByName + ;; + loginUser) + call_loginUser + ;; + logoutUser) + call_logoutUser + ;; + updateUser) + call_updateUser + ;; + *) + echo "Error: Unknown operation: $operation" + echo "" + print_help + exit 1 +esac + diff --git a/samples/client/petstore/bash/petstore-cli.bash-completion b/samples/client/petstore/bash/petstore-cli.bash-completion new file mode 100644 index 00000000000..cdb743c60b2 --- /dev/null +++ b/samples/client/petstore/bash/petstore-cli.bash-completion @@ -0,0 +1,286 @@ +# petstore-cli completion -*- shell-script -*- + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: 2017-01-12T00:07:27.471+01:00 +# ! +# ! +# ! System wide installation: +# ! +# ! $ sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +# ! +# ! +# ! User home installation (add this line to .bash_profile): +# ! +# ! [ -r ~/petstore-cli.bash-completion ] && source ~/petstore-cli.bash-completion +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + + +__osx_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword +} + + +_petstore-cli() +{ + local cur + local prev + local words + local cword + + #words="${COMP_WORDS}" + #cword="${COMP_CWORD}" + #prev="${COMP_WORDS[COMP_CWORD-1]}" + #cur="${COMP_WORDS[COMP_CWORD]}" + + # The reference of currently selected REST operation + local operation="" + + # The list of available operation in the REST service + # It's modelled as an associative array for efficient key lookup + declare -A operations + operations["testClientModel"]=1 + operations["testEndpointParameters"]=1 + operations["testEnumParameters"]=1 + operations["addPet"]=1 + operations["deletePet"]=1 + operations["findPetsByStatus"]=1 + operations["findPetsByTags"]=1 + operations["getPetById"]=1 + operations["updatePet"]=1 + operations["updatePetWithForm"]=1 + operations["uploadFile"]=1 + operations["deleteOrder"]=1 + operations["getInventory"]=1 + operations["getOrderById"]=1 + operations["placeOrder"]=1 + operations["createUser"]=1 + operations["createUsersWithArrayInput"]=1 + operations["createUsersWithListInput"]=1 + operations["deleteUser"]=1 + operations["getUserByName"]=1 + operations["loginUser"]=1 + operations["logoutUser"]=1 + operations["updateUser"]=1 + + # An associative array of operations to their parameters + # Only include path, query and header parameters + declare -A operation_parameters + operation_parameters["testClientModel"]="" + operation_parameters["testEndpointParameters"]="" + operation_parameters["testEnumParameters"]="enum_query_string_array= enum_query_string= enum_query_integer= enum_header_string_array: enum_header_string: " + operation_parameters["addPet"]="" + operation_parameters["deletePet"]="petId= api_key: " + operation_parameters["findPetsByStatus"]="status= " + operation_parameters["findPetsByTags"]="tags= " + operation_parameters["getPetById"]="petId= " + operation_parameters["updatePet"]="" + operation_parameters["updatePetWithForm"]="petId= " + operation_parameters["uploadFile"]="petId= " + operation_parameters["deleteOrder"]="orderId= " + operation_parameters["getInventory"]="" + operation_parameters["getOrderById"]="orderId= " + operation_parameters["placeOrder"]="" + operation_parameters["createUser"]="" + operation_parameters["createUsersWithArrayInput"]="" + operation_parameters["createUsersWithListInput"]="" + operation_parameters["deleteUser"]="username= " + operation_parameters["getUserByName"]="username= " + operation_parameters["loginUser"]="username= password= " + operation_parameters["logoutUser"]="" + operation_parameters["updateUser"]="username= " + + # An associative array of possible values for enum parameters + declare -A operation_parameters_enum_values + + # + # Check if the _init_completion function is available, which is + # available since bash-completion 1.4 + # + if declare -F _init_completions >/dev/null 2>&1; then + _init_completion -s || return + else + __osx_init_completion || return + fi + + + # Check if operation is already in the command line provided + for word in "${words[@]}"; do + if [[ -n $word && ${operations[$word]} ]]; then + operation="${word}" + fi + done + + if [[ -z $operation ]]; then + case $prev in + --ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\ + --ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\ + --help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\ + --mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\ + --pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\ + --range|-X|--request|--retry|--retry-delay|--retry-max-time|\ + --socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\ + --time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\ + --write-out|--resolve|--tlsuser|--tlspassword|--about) + return + ;; + -K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\ + --key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\ + --trace-ascii|--netrc-file) + _filedir + return + ;; + --cacert|-E|--cert) + _filedir '@(c?(e)rt|cer|pem|der)' + return + ;; + --capath) + _filedir -d + return + ;; + --cert-type|--key-type) + COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) ) + return + ;; + --crlfile) + _filedir crl + return + ;; + -d|--data|--data-ascii|--data-binary|--data-urlencode) + if [[ $cur == \@* ]]; then + cur=${cur:1} + _filedir + COMPREPLY=( "${COMPREPLY[@]/#/@}" ) + fi + return + ;; + --delegation) + COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) ) + return + ;; + --engine) + COMPREPLY=( $( compgen -W 'list' -- "$cur" ) ) + return + ;; + --ftp-method) + COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) ) + return + ;; + --ftp-ssl-ccc-mode) + COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) ) + return + ;; + --interface) + _available_interfaces -a + return + ;; + -x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname) + _known_hosts_real + return + ;; + --pubkey) + _filedir pub + return + ;; + --stderr) + COMPREPLY=( $( compgen -W '-' -- "$cur" ) ) + _filedir + return + ;; + --tlsauthtype) + COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) ) + return + ;; + --host) + COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) ) + return + ;; + -ct|--content-type|-ac|--accept) + COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) ) + return + ;; + esac + fi + + # + # Complete the server address based on ~/.ssh/known_hosts + # and ~/.ssh/config + # + # \todo Fix - cur matches only '//' when $prev is ':' + # + if [[ "$cur" == "http://" || "$cur" == "https://" ]]; then + COMPREPLY=() + local comp_ssh_hosts=`cat ~/.ssh/known_hosts | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ; + cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}'` + COMPREPLY=( $(compgen -W "${comp_ssh_hosts}" -- $cur)) + return + fi + + # + # Complete the petstore-cli and cURL's arguments + # + if [[ $cur == -* ]]; then + COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) ) + return + fi + + # + # If the argument starts with a letter this could be either an operation + # or an operation parameter + # When $cur is empty, suggest the list of operations by default + # + if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then + # If operation has not been yet selected, suggest the list of operations + # otherwise suggest arguments of this operation as declared in the + # Swagger specification + if [[ -z $operation ]]; then + COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) + else + COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + fi + return + fi + +} && +complete -F _petstore-cli petstore-cli + +# ex: ts=4 sw=4 et filetype=sh \ No newline at end of file diff --git a/samples/client/petstore/bash/pom.xml b/samples/client/petstore/bash/pom.xml new file mode 100644 index 00000000000..fc8237d186c --- /dev/null +++ b/samples/client/petstore/bash/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + io.swagger + BashPetstoreClientTests + pom + 1.0-SNAPSHOT + Bash Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bats-test + integration-test + + exec + + + bats + + --tap + tests/petstore_test.sh + + + + + + + + diff --git a/samples/client/petstore/bash/tests/petstore_test.sh b/samples/client/petstore/bash/tests/petstore_test.sh new file mode 100644 index 00000000000..139679eb3ee --- /dev/null +++ b/samples/client/petstore/bash/tests/petstore_test.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bats + + +export PETSTORE_CLI="petstore-cli" + +export PETSTORE_HOST="http://petstore.swagger.io" + + +# +# Tests for parameter handling and validation +# +@test "addPet without host" { + unset PETSTORE_HOST + run bash $PETSTORE_CLI -ac xml -ct json \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "Error: No hostname provided!!!" ]] +} + +@test "addPet without content type" { + run bash $PETSTORE_CLI -ac xml --host $PETSTORE_HOST \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "Error: Request's content-type not specified!" ]] +} + +@test "fakeOperation invalid operation name" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io fakeOperation" + [[ "$output" =~ "Error: No operation specified!" ]] +} + +@test "findPetsByStatus basic auth" { + run bash \ + -c "bash $PETSTORE_CLI -u alice:secret --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run" + [[ "$output" =~ "-u alice:secret" ]] +} + +@test "findPetsByStatus api key" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 api_key:1234 --dry-run" + [[ "$output" =~ "-H \"api_key: 1234\"" ]] +} + +@test "findPetsByStatus empty api key" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run" + [[ ! "$output" =~ "-H \"api_key:" ]] +} + + + + +@test "findPetsByStatus too few values" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus" + [[ "$output" =~ "Error: Too few values" ]] +} + +@test "findPetsByTags too few values" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags" + [[ "$output" =~ "Error: Too few values" ]] +} + +@test "findPetsByStatus status with space" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus \ + status=available status=\"gone test\" --dry-run" + [[ "$output" =~ "status=available,gone%20test" ]] +} + +@test "findPetsByStatus collection csv" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \ + tags=TAG1 tags=TAG2 --dry-run" + [[ "$output" =~ "tags=TAG1,TAG2" ]] +} + +@test "findPetsByStatus collection csv with space and question mark" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \ + tags=TAG1 tags=\"TAG2 TEST\" tags=TAG3?TEST --dry-run" + [[ "$output" =~ "tags=TAG1,TAG2%20TEST,TAG3%3FTEST" ]] +} + +# +# Operations calling the service and checking result +# +@test "addPet from parameters" { + run bash $PETSTORE_CLI -ct json -ac xml \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "123321" ]] +} + +@test "addPet from pipe" { + run bash \ + -c "echo '{\"id\": 37567, \"name\": \"lucky\", \"status\": \"available\"}' | \ + bash $PETSTORE_CLI -ct json -ac xml addPet -" + [[ "$output" =~ "37567" ]] +} + + + From 9bb58d204038c7bee8ed84aa4c1f55343d8529c8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 12 Jan 2017 23:36:43 +0800 Subject: [PATCH 235/269] add git tip --- CONTRIBUTING.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 83166fa1a53..e0b6576bf95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -76,3 +76,5 @@ To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all t - Document the fix in the code to make the code more readable - Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) - File a PR with meaningful title, description and commit messages. A good example is [PR-3306](https://github.com/swagger-api/swagger-codegen/pull/3306) +- Recommended git settings + - `git config --global core.autocrlf input` to tell Git convert CRLF to LF on commit but not the other way around From af4319015e0c1ab6da03083d793e465b7ca58def Mon Sep 17 00:00:00 2001 From: eblis Date: Thu, 12 Jan 2017 18:11:07 +0200 Subject: [PATCH 236/269] When reading mustache template files assume UTF-8 encoding, fixes #4544. (#4545) --- .../src/main/java/io/swagger/codegen/AbstractGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 849651baa9d..abf77b59cb1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -56,7 +56,7 @@ public abstract class AbstractGenerator { if (is == null) { is = new FileInputStream(new File(name)); // May throw but never return a null value } - return new InputStreamReader(is); + return new InputStreamReader(is, "UTF-8"); } catch (Exception e) { LOGGER.error(e.getMessage()); } From 39b76ece22071eee9073976d50452239cf6334ab Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 13 Jan 2017 00:30:56 +0800 Subject: [PATCH 237/269] add space before C# in readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e9c68acc931..f260d4dec42 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: **ActionScript**, **Bash**,**C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) +- **API clients**: **ActionScript**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) - **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** From d40f7a41b6866364265d7fbc55f21a32e14066ba Mon Sep 17 00:00:00 2001 From: Joseph Moore Date: Fri, 13 Jan 2017 08:01:15 -0700 Subject: [PATCH 238/269] Add triple-mustache to all instances of vendorExtensions.extraAnnotation. (#4553) This covers the usages that weren't fixed in #3825 Triple mustache is required because annotations may contain chars like "=" that would be mistakenly encoded. --- .../src/main/resources/JavaInflector/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/cxf/pojo.mustache | 2 +- .../swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/resteasy/pojo.mustache | 2 +- .../src/main/resources/JavaJaxRS/spec/pojo.mustache | 2 +- .../swagger-codegen/src/main/resources/JavaSpring/pojo.mustache | 2 +- modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache | 2 +- .../swagger-codegen/src/main/resources/undertow/pojo.mustache | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache index f736844264b..56869755b79 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache @@ -34,7 +34,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache index f1d68d014e7..a62db41bd53 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -21,7 +21,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index b959ce17c15..2d74634919c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -47,7 +47,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index 489dd2ac82f..b6ae4ee132c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -64,7 +64,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} {{#jackson}} @JsonProperty("{{baseName}}") diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache index 63578d8bc73..b51330b49c6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache @@ -13,7 +13,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache index f5657c2d33f..d763209f030 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -21,7 +21,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache index 06c8e3048a0..dc5feda5539 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache @@ -62,7 +62,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache index 6e5c1b74115..7545ad82098 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache @@ -64,7 +64,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache index 58bfed16381..e63ecfe2f47 100644 --- a/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache @@ -19,7 +19,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { From 2e7e25801d18c4109df17ca375d9c8e5a264cbf4 Mon Sep 17 00:00:00 2001 From: Richard Naeve Date: Fri, 13 Jan 2017 16:41:54 +0100 Subject: [PATCH 239/269] Issue 4531 (#4539) * ISSUE-4531 Arrays are now serialized according to the different collection formats. All api classes are also exported in a const array to make handling of large api libraries easier. * Added petstore samples * Fixed indentations and coding style --- .../typescript-angular2/api.mustache | 70 ++++++++--- .../typescript-angular2/apis.mustache | 2 + .../typescript-angular2/variables.mustache | 8 +- .../typescript-angular2/default/api/PetApi.ts | 109 ++++++------------ .../default/api/StoreApi.ts | 35 +----- .../default/api/UserApi.ts | 62 ++-------- .../typescript-angular2/default/api/api.ts | 4 + .../typescript-angular2/default/variables.ts | 8 +- .../typescript-angular2/npm/README.md | 4 +- .../typescript-angular2/npm/api/PetApi.ts | 109 ++++++------------ .../typescript-angular2/npm/api/StoreApi.ts | 35 +----- .../typescript-angular2/npm/api/UserApi.ts | 62 ++-------- .../typescript-angular2/npm/api/api.ts | 4 + .../typescript-angular2/npm/package.json | 2 +- .../typescript-angular2/npm/variables.ts | 8 +- 15 files changed, 194 insertions(+), 328 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index 8700083b63d..d62224930ef 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -8,7 +8,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -93,15 +93,36 @@ export class {{classname}} { {{/required}} {{/allParams}} {{#queryParams}} + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + queryParameters.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + queryParameters.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} + } + {{/isListContainer}} + {{^isListContainer}} if ({{paramName}} !== undefined) { queryParameters.set('{{baseName}}', {{paramName}}); } + {{/isListContainer}} + {{/queryParams}} - {{#headerParams}} + {{#isListContainer}} + if ({{paramName}}) { + headers.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + } + {{/isListContainer}} + {{^isListContainer}} headers.set('{{baseName}}', String({{paramName}})); -{{/headerParams}} + {{/isListContainer}} +{{/headerParams}} // to determine the Content-Type header let consumes: string[] = [ {{#consumes}} @@ -120,51 +141,64 @@ export class {{classname}} { // authentication ({{name}}) required {{#isApiKey}} {{#isKeyInHeader}} - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('{{keyParamName}}', this.configuration.apiKey); } + {{/isKeyInHeader}} {{#isKeyInQuery}} - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { formParams.set('{{keyParamName}}', this.configuration.apiKey); } + {{/isKeyInQuery}} {{/isApiKey}} {{#isBasic}} // http basic authentication required - if (this.configuration.username || this.configuration.password) - { + if (this.configuration.username || this.configuration.password) { headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } + {{/isBasic}} {{#isOAuth}} // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + {{/isOAuth}} {{/authMethods}} - {{#hasFormParams}} headers.set('Content-Type', 'application/x-www-form-urlencoded'); -{{/hasFormParams}} +{{/hasFormParams}} {{#bodyParam}} headers.set('Content-Type', 'application/json'); + {{/bodyParam}} - {{#formParams}} - if ({{paramName}} !== undefined) { - formParams.set('{{baseName}}', {{paramName}}); + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + formParams.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + formParams.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} } -{{/formParams}} + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + formParams.set('{{baseName}}', {{paramName}}); + } + {{/isListContainer}} +{{/formParams}} let requestOptions: RequestOptionsArgs = new RequestOptions({ method: {{httpMethod}}, headers: headers, @@ -184,7 +218,7 @@ export class {{classname}} { return this.http.request(path, requestOptions); } - + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache index 9a39b864538..85522cf6c58 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache @@ -2,6 +2,8 @@ {{#apis}} {{#operations}} export * from './{{ classname }}'; +import { {{ classname }} } from './{{ classname }}'; {{/operations}} {{/apis}} +export const APIS = [ {{#apis}}{{#operations}}{{ classname }}, {{/operations}}{{/apis}}]; {{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache index 27b987e9b23..944e688f1b1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 5751b452369..535d21d66d0 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -199,8 +199,6 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ 'application/json', @@ -215,18 +213,15 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -241,7 +236,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Deletes a pet * @@ -257,7 +252,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headers.set('api_key', String(apiKey)); // to determine the Content-Type header @@ -272,16 +266,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -296,7 +286,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -307,11 +297,12 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (status !== undefined) { - queryParameters.set('status', status); + if (status) { + status.forEach((element) => { + queryParameters.append('status', element); + }) } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -324,16 +315,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -348,7 +335,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -359,11 +346,12 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (tags !== undefined) { - queryParameters.set('tags', tags); + if (tags) { + tags.forEach((element) => { + queryParameters.append('tags', element); + }) } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -376,16 +364,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -400,7 +384,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions @@ -415,8 +399,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -427,23 +409,19 @@ export class PetApi { 'application/xml' ]; + // authentication (api_key) required + if (this.configuration.apiKey) { + headers.set('api_key', this.configuration.apiKey); + } + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -458,7 +436,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Update an existing pet * @@ -469,8 +447,6 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ 'application/json', @@ -485,18 +461,15 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, @@ -511,7 +484,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Updates a pet in the store with form data * @@ -530,8 +503,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' @@ -545,22 +516,21 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + headers.set('Content-Type', 'application/x-www-form-urlencoded'); - if (name !== undefined) { - formParams.set('name', name); + formParams.set('name', name); } + if (status !== undefined) { - formParams.set('status', status); + formParams.set('status', status); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -577,7 +547,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * uploads an image * @@ -596,8 +566,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' @@ -611,22 +579,21 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + headers.set('Content-Type', 'application/x-www-form-urlencoded'); - if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata); + formParams.set('additionalMetadata', additionalMetadata); } + if (file !== undefined) { - formParams.set('file', file); + formParams.set('file', file); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -643,5 +610,5 @@ export class PetApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 484d5e56fde..344d1f1b257 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -133,8 +133,6 @@ export class StoreApi { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -145,10 +143,6 @@ export class StoreApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -162,7 +156,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -172,8 +166,6 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -185,13 +177,9 @@ export class StoreApi { ]; // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -206,7 +194,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -221,8 +209,6 @@ export class StoreApi { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -233,10 +219,6 @@ export class StoreApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -250,7 +232,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Place an order for a pet * @@ -261,8 +243,6 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -273,11 +253,8 @@ export class StoreApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -292,5 +269,5 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index 8dda0cf8377..bb7884ea636 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -195,8 +195,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -207,11 +205,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -226,7 +221,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Creates list of users with given input array * @@ -237,8 +232,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -249,11 +242,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -268,7 +258,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Creates list of users with given input array * @@ -279,8 +269,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -291,11 +279,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -310,7 +295,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Delete user * This can only be done by the logged in user. @@ -325,8 +310,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -337,10 +320,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -354,7 +333,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Get user by user name * @@ -369,8 +348,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -381,10 +358,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -398,7 +371,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Logs user into the system * @@ -413,11 +386,11 @@ export class UserApi { if (username !== undefined) { queryParameters.set('username', username); } + if (password !== undefined) { queryParameters.set('password', password); } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -428,10 +401,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -445,7 +414,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Logs out current logged in user session * @@ -455,8 +424,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -467,10 +434,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -484,7 +447,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Updated user * This can only be done by the logged in user. @@ -500,8 +463,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -512,11 +473,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, @@ -531,5 +489,5 @@ export class UserApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/default/api/api.ts b/samples/client/petstore/typescript-angular2/default/api/api.ts index 056206bfaca..0d1e9f047fd 100644 --- a/samples/client/petstore/typescript-angular2/default/api/api.ts +++ b/samples/client/petstore/typescript-angular2/default/api/api.ts @@ -1,3 +1,7 @@ export * from './PetApi'; +import { PetApi } from './PetApi'; export * from './StoreApi'; +import { StoreApi } from './StoreApi'; export * from './UserApi'; +import { UserApi } from './UserApi'; +export const APIS = [ PetApi, StoreApi, UserApi, ]; diff --git a/samples/client/petstore/typescript-angular2/default/variables.ts b/samples/client/petstore/typescript-angular2/default/variables.ts index 27b987e9b23..944e688f1b1 100644 --- a/samples/client/petstore/typescript-angular2/default/variables.ts +++ b/samples/client/petstore/typescript-angular2/default/variables.ts @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 5f176a7b484..b1cac56e5e8 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612150011 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701111439 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201612150011 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701111439 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 5751b452369..535d21d66d0 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -199,8 +199,6 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ 'application/json', @@ -215,18 +213,15 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -241,7 +236,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Deletes a pet * @@ -257,7 +252,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headers.set('api_key', String(apiKey)); // to determine the Content-Type header @@ -272,16 +266,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, @@ -296,7 +286,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Finds Pets by status * Multiple status values can be provided with comma separated strings @@ -307,11 +297,12 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (status !== undefined) { - queryParameters.set('status', status); + if (status) { + status.forEach((element) => { + queryParameters.append('status', element); + }) } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -324,16 +315,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -348,7 +335,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -359,11 +346,12 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (tags !== undefined) { - queryParameters.set('tags', tags); + if (tags) { + tags.forEach((element) => { + queryParameters.append('tags', element); + }) } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -376,16 +364,12 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -400,7 +384,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Find pet by ID * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions @@ -415,8 +399,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -427,23 +409,19 @@ export class PetApi { 'application/xml' ]; + // authentication (api_key) required + if (this.configuration.apiKey) { + headers.set('api_key', this.configuration.apiKey); + } + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -458,7 +436,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Update an existing pet * @@ -469,8 +447,6 @@ export class PetApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ 'application/json', @@ -485,18 +461,15 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, @@ -511,7 +484,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * Updates a pet in the store with form data * @@ -530,8 +503,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' @@ -545,22 +516,21 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + headers.set('Content-Type', 'application/x-www-form-urlencoded'); - if (name !== undefined) { - formParams.set('name', name); + formParams.set('name', name); } + if (status !== undefined) { - formParams.set('status', status); + formParams.set('status', status); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -577,7 +547,7 @@ export class PetApi { return this.http.request(path, requestOptions); } - + /** * uploads an image * @@ -596,8 +566,6 @@ export class PetApi { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' @@ -611,22 +579,21 @@ export class PetApi { // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + headers.set('Content-Type', 'application/x-www-form-urlencoded'); - if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata); + formParams.set('additionalMetadata', additionalMetadata); } + if (file !== undefined) { - formParams.set('file', file); + formParams.set('file', file); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -643,5 +610,5 @@ export class PetApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 484d5e56fde..344d1f1b257 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -133,8 +133,6 @@ export class StoreApi { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -145,10 +143,6 @@ export class StoreApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -162,7 +156,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Returns pet inventories by status * Returns a map of status codes to quantities @@ -172,8 +166,6 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -185,13 +177,9 @@ export class StoreApi { ]; // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, @@ -206,7 +194,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Find purchase order by ID * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -221,8 +209,6 @@ export class StoreApi { if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -233,10 +219,6 @@ export class StoreApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -250,7 +232,7 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + /** * Place an order for a pet * @@ -261,8 +243,6 @@ export class StoreApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -273,11 +253,8 @@ export class StoreApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -292,5 +269,5 @@ export class StoreApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index 8dda0cf8377..bb7884ea636 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -19,7 +19,7 @@ import { Observable } from 'rxjs/Observab import 'rxjs/add/operator/map'; import * as models from '../model/models'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -195,8 +195,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -207,11 +205,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -226,7 +221,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Creates list of users with given input array * @@ -237,8 +232,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -249,11 +242,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -268,7 +258,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Creates list of users with given input array * @@ -279,8 +269,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -291,11 +279,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, @@ -310,7 +295,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Delete user * This can only be done by the logged in user. @@ -325,8 +310,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -337,10 +320,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, @@ -354,7 +333,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Get user by user name * @@ -369,8 +348,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -381,10 +358,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -398,7 +371,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Logs user into the system * @@ -413,11 +386,11 @@ export class UserApi { if (username !== undefined) { queryParameters.set('username', username); } + if (password !== undefined) { queryParameters.set('password', password); } - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -428,10 +401,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -445,7 +414,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Logs out current logged in user session * @@ -455,8 +424,6 @@ export class UserApi { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -467,10 +434,6 @@ export class UserApi { 'application/xml' ]; - - - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -484,7 +447,7 @@ export class UserApi { return this.http.request(path, requestOptions); } - + /** * Updated user * This can only be done by the logged in user. @@ -500,8 +463,6 @@ export class UserApi { if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - - // to determine the Content-Type header let consumes: string[] = [ ]; @@ -512,11 +473,8 @@ export class UserApi { 'application/xml' ]; - - headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, @@ -531,5 +489,5 @@ export class UserApi { return this.http.request(path, requestOptions); } - + } diff --git a/samples/client/petstore/typescript-angular2/npm/api/api.ts b/samples/client/petstore/typescript-angular2/npm/api/api.ts index 056206bfaca..0d1e9f047fd 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/api.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/api.ts @@ -1,3 +1,7 @@ export * from './PetApi'; +import { PetApi } from './PetApi'; export * from './StoreApi'; +import { StoreApi } from './StoreApi'; export * from './UserApi'; +import { UserApi } from './UserApi'; +export const APIS = [ PetApi, StoreApi, UserApi, ]; diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 6dd91bb3f86..e6d3d71d494 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201612150011", + "version": "0.0.1-SNAPSHOT.201701111439", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ diff --git a/samples/client/petstore/typescript-angular2/npm/variables.ts b/samples/client/petstore/typescript-angular2/npm/variables.ts index 27b987e9b23..944e688f1b1 100644 --- a/samples/client/petstore/typescript-angular2/npm/variables.ts +++ b/samples/client/petstore/typescript-angular2/npm/variables.ts @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file From 95987fc132cab95dfec9af8d301a8ba1d271b536 Mon Sep 17 00:00:00 2001 From: Gene Chang Date: Fri, 13 Jan 2017 11:07:06 -0500 Subject: [PATCH 240/269] Added support for datetime query parameters in cpprest (#4556) * Added support for datetime query parameters in cpprest Signed-off-by: Gene Chang * Update petstore sample app for cpprest using bin/cpprest-petstore.sh Signed-off-by: Gene Chang --- .../src/main/resources/cpprest/apiclient-header.mustache | 1 + .../src/main/resources/cpprest/apiclient-source.mustache | 5 +++++ samples/client/petstore/cpprest/ApiClient.cpp | 5 +++++ samples/client/petstore/cpprest/ApiClient.h | 1 + samples/client/petstore/cpprest/api/PetApi.cpp | 2 +- samples/client/petstore/cpprest/api/PetApi.h | 4 ++-- samples/client/petstore/cpprest/api/StoreApi.h | 4 ++-- samples/client/petstore/cpprest/model/Category.cpp | 2 +- samples/client/petstore/cpprest/model/Order.cpp | 4 ++-- samples/client/petstore/cpprest/model/Pet.cpp | 2 +- samples/client/petstore/cpprest/model/Pet.h | 6 +++--- samples/client/petstore/cpprest/model/Tag.cpp | 2 +- samples/client/petstore/cpprest/model/User.cpp | 2 +- 13 files changed, 26 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache index 466f914d4a9..91400f163aa 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -38,6 +38,7 @@ public: static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(const utility::datetime &value); template static utility::string_t parameterToArrayString(std::vector value) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache index e9a3810c7bd..4f86ad40540 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -40,6 +40,11 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + pplx::task ApiClient::callApi( const utility::string_t& path, const utility::string_t& method, diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index c7687e2851b..00798258261 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -52,6 +52,11 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + pplx::task ApiClient::callApi( const utility::string_t& path, const utility::string_t& method, diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 81b38cb09c5..1678e9e8c51 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -50,6 +50,7 @@ public: static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(const utility::datetime &value); template static utility::string_t parameterToArrayString(std::vector value) diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index aa9aab9d89c..c423c43e173 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -438,7 +438,7 @@ pplx::task>> PetApi::findPetsByTags(std::vector { - queryParams[U("tags")] = ApiClient::parameterToArrayString(tags); + queryParams[U("tags")] = ApiClient::parameterToArrayString<>(tags); } std::shared_ptr httpBody; diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index d60c3c80fca..0a783c66a29 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -22,10 +22,10 @@ #include "ApiClient.h" -#include "ApiResponse.h" -#include "HttpContent.h" #include "Pet.h" #include +#include "ApiResponse.h" +#include "HttpContent.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 60ec088b326..99cbedea460 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -22,9 +22,9 @@ #include "ApiClient.h" -#include "Order.h" -#include #include +#include +#include "Order.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index bdb6d8e894a..9c0f21b3b22 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -21,7 +21,7 @@ namespace model { Category::Category() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index e21d867cd7e..07e815fa90c 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -21,9 +21,9 @@ namespace model { Order::Order() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; - m_PetId = 0; + m_PetId = 0L; m_PetIdIsSet = false; m_Quantity = 0; m_QuantityIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 51dd6d883e9..74b707a4c26 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -21,7 +21,7 @@ namespace model { Pet::Pet() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_CategoryIsSet = false; m_Name = U(""); diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index 91704dc9ed7..065c46bdb93 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -22,10 +22,10 @@ #include "ModelBase.h" -#include "Category.h" -#include -#include #include "Tag.h" +#include +#include "Category.h" +#include namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 3cb0798c99e..466ca0d29da 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -21,7 +21,7 @@ namespace model { Tag::Tag() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 1ea09f35b50..e9c5e969673 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -21,7 +21,7 @@ namespace model { User::User() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Username = U(""); m_UsernameIsSet = false; From d7e6a3da6aa0600c08c228a1f83b1578bf24587b Mon Sep 17 00:00:00 2001 From: eamon316 Date: Sun, 15 Jan 2017 15:25:30 +0000 Subject: [PATCH 241/269] Add a useTags flag to allow tags to be used to generate interface / controller classnames (#4396) --- .../io/swagger/codegen/languages/SpringCodegen.java | 13 ++++++++++++- .../codegen/options/SpringOptionsProvider.java | 2 ++ .../swagger/codegen/spring/SpringOptionsTest.java | 2 ++ 3 files changed, 16 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 0f64795e369..cf2ff55e7c5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -18,6 +18,7 @@ public class SpringCodegen extends AbstractJavaCodegen { public static final String JAVA_8 = "java8"; public static final String ASYNC = "async"; public static final String RESPONSE_WRAPPER = "responseWrapper"; + public static final String USE_TAGS = "useTags"; public static final String SPRING_MVC_LIBRARY = "spring-mvc"; public static final String SPRING_CLOUD_LIBRARY = "spring-cloud"; @@ -29,6 +30,7 @@ public class SpringCodegen extends AbstractJavaCodegen { protected boolean java8 = false; protected boolean async = false; protected String responseWrapper = ""; + protected boolean useTags = false; public SpringCodegen() { super(); @@ -54,6 +56,7 @@ public class SpringCodegen extends AbstractJavaCodegen { cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); + cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames")); supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); @@ -124,6 +127,10 @@ public class SpringCodegen extends AbstractJavaCodegen { this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER)); } + if (additionalProperties.containsKey(USE_TAGS)) { + this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString())); + } + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -221,7 +228,7 @@ public class SpringCodegen extends AbstractJavaCodegen { @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - if(library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) { + if((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -400,6 +407,10 @@ public class SpringCodegen extends AbstractJavaCodegen { public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; } + public void setUseTags(boolean useTags) { + this.useTags = useTags; + } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index de7caa0d6c7..55ef56bf505 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -16,6 +16,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { public static final String JAVA_8 = "true"; public static final String ASYNC = "true"; public static final String RESPONSE_WRAPPER = "Callable"; + public static final String USE_TAGS = "useTags"; @Override public String getLanguage() { @@ -34,6 +35,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { options.put(SpringCodegen.JAVA_8, JAVA_8); options.put(SpringCodegen.ASYNC, ASYNC); options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER); + options.put(SpringCodegen.USE_TAGS, USE_TAGS); return options; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 4084c0a80e9..65894ba558f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -66,6 +66,8 @@ public class SpringOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); times = 1; + clientCodegen.setUseTags(Boolean.valueOf(SpringOptionsProvider.USE_TAGS)); + times = 1; }}; } From 663b471d1a49832b60ada7ffaf98d8e37c84e6ed Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 15 Jan 2017 09:35:43 -0600 Subject: [PATCH 242/269] [nancyfx/csharp] Customize interface prefix (#4557) Per #4486, this allows user to specify the use of a standard or custom prefix for interfaces. For C# based languages, this follows Microsoft's Framework Design Guidelines and uses an I- prefix. However, to avoid breaking changes with existing nancyfx generated code, the default is unset. The option supports true, false, or a custom prefix. --- bin/nancyfx-petstore-server.sh | 2 +- .../io/swagger/codegen/CodegenConstants.java | 3 +++ .../languages/AbstractCSharpCodegen.java | 22 +++++++++++++++++++ .../languages/CSharpClientCodegen.java | 4 ++++ .../languages/NancyFXServerCodegen.java | 19 +++++----------- .../src/main/resources/csharp/api.mustache | 4 ++-- .../src/main/resources/nancyfx/api.mustache | 4 ++-- .../csharp/CSharpClientOptionsTest.java | 2 ++ .../options/CSharpClientOptionsProvider.java | 1 + .../options/NancyFXServerOptionsProvider.java | 11 +++------- 10 files changed, 45 insertions(+), 27 deletions(-) diff --git a/bin/nancyfx-petstore-server.sh b/bin/nancyfx-petstore-server.sh index 20797fa0c1f..2b9b2994cbf 100755 --- a/bin/nancyfx-petstore-server.sh +++ b/bin/nancyfx-petstore-server.sh @@ -26,6 +26,6 @@ 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 -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx" java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 094ff38e8fd..f5c759d4d04 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -86,6 +86,9 @@ public class CodegenConstants { public static final String USE_COLLECTION = "useCollection"; public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection instead of List."; + public static final String INTERFACE_PREFIX = "interfacePrefix"; + public static final String INTERFACE_PREFIX_DESC = "Prefix interfaces with a community standard or widely accepted prefix."; + public static final String RETURN_ICOLLECTION = "returnICollection"; public static final String RETURN_ICOLLECTION_DESC = "Return ICollection instead of the concrete type."; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 71c35053988..746edebc9ca 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -27,6 +27,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected String packageCompany = "Swagger"; protected String packageCopyright = "No Copyright"; + protected String interfacePrefix = "I"; + protected String sourceFolder = "src"; // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. @@ -254,6 +256,18 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) { setOptionalEmitDefaultValue(Boolean.valueOf(additionalProperties.get(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES).toString())); } + + if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { + String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); + if("false".equals(useInterfacePrefix)) { + setInterfacePrefix(""); + } else if(!"true".equals(useInterfacePrefix)) { + // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. + setInterfacePrefix(sanitizeName(useInterfacePrefix)); + } + + additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); + } } @Override @@ -616,6 +630,14 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co this.sourceFolder = sourceFolder; } + public String getInterfacePrefix() { + return interfacePrefix; + } + + public void setInterfacePrefix(final String interfacePrefix) { + this.interfacePrefix = interfacePrefix; + } + @Override public String toEnumVarName(String name, String datatype) { if (name.length() == 0) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index c70749392cf..cf4bc656d83 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -72,6 +72,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, null); + addOption(CodegenConstants.INTERFACE_PREFIX, + CodegenConstants.INTERFACE_PREFIX_DESC, + interfacePrefix); + CliOption framework = new CliOption( CodegenConstants.DOTNET_FRAMEWORK, CodegenConstants.DOTNET_FRAMEWORK_DESC diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 44f31b25eb6..ace3ccaa4e2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -1,20 +1,7 @@ package io.swagger.codegen.languages; import static com.google.common.base.Strings.isNullOrEmpty; -import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE; -import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE_DESC; -import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME; -import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION_DESC; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER_DESC; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION_DESC; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET_DESC; +import static io.swagger.codegen.CodegenConstants.*; import static io.swagger.codegen.CodegenType.SERVER; import static java.util.Arrays.asList; import static java.util.UUID.randomUUID; @@ -71,6 +58,9 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); + // Early versions use no prefix for interfaces. Defaulting to I- common practice would break existing users. + setInterfacePrefix(""); + // contextually reserved words setReservedWordsLowerCase( asList("var", "async", "await", "dynamic", "yield") @@ -82,6 +72,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { addOption(PACKAGE_NAME, "C# package name (convention: Title.Case).", packageName); addOption(PACKAGE_VERSION, "C# package version.", packageVersion); addOption(SOURCE_FOLDER, SOURCE_FOLDER_DESC, sourceFolder); + addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); // CLI Switches addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f62cabe42e0..18c949980cb 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -14,7 +14,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public interface I{{classname}} : IApiAccessor + public interface {{interfacePrefix}}{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} @@ -73,7 +73,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class {{classname}} : I{{classname}} + public partial class {{classname}} : {{interfacePrefix}}{{classname}} { private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index b4213ff2056..3aca8b8855e 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -40,7 +40,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// /// Service handling {{classname}} requests. /// - public interface {{classname}}Service + public interface {{interfacePrefix}}{{classname}}Service { {{#operation}}///
    /// {{notes}} @@ -56,7 +56,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// /// Abstraction of {{classname}}Service. /// - public abstract class Abstract{{classname}}Service: {{classname}}Service + public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service { {{#operation}}public virtual {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index f53ac5e0626..8bc55f211be 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -50,6 +50,8 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGeneratePropertyChanged(true); times = 1; + clientCodegen.setInterfacePrefix("X"); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index a438a31e2b7..9bbc6512911 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -35,6 +35,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.GENERATE_PROPERTY_CHANGED, "true") + .put(CodegenConstants.INTERFACE_PREFIX, "X") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java index 77a374f648e..4185de846c7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java @@ -1,17 +1,11 @@ package io.swagger.codegen.options; -import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME; -import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET; - import java.util.Map; import com.google.common.collect.ImmutableMap; +import static io.swagger.codegen.CodegenConstants.*; + public class NancyFXServerOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_server_nancyfx"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; @@ -32,6 +26,7 @@ public class NancyFXServerOptionsProvider implements OptionsProvider { .put(USE_DATETIME_OFFSET, "true") .put(USE_COLLECTION, "false") .put(RETURN_ICOLLECTION, "false") + .put(INTERFACE_PREFIX, "X") .build(); } From f0cddd21fd96b49cfea7ad70f32007f36b540f3d Mon Sep 17 00:00:00 2001 From: Tomek Cejner Date: Sun, 15 Jan 2017 18:01:50 +0100 Subject: [PATCH 243/269] Swift3 Clener template of client methods (#4552) * Swift3 template properly uploads files, making mustache template little cleaner * [swift3] moved URL parameter encoder helper function to APIHelper.swift * Swift3 - regenerated sample --- .../main/resources/swift3/APIHelper.mustache | 9 ++ .../src/main/resources/swift3/api.mustache | 39 ++++---- .../Classes/Swaggers/APIHelper.swift | 9 ++ .../Classes/Swaggers/APIs/FakeAPI.swift | 49 +++++----- .../Classes/Swaggers/APIs/PetAPI.swift | 89 +++++++------------ .../Classes/Swaggers/APIs/StoreAPI.swift | 41 +++------ .../Classes/Swaggers/APIs/UserAPI.swift | 72 +++++---------- .../Classes/Swaggers/Models.swift | 19 ++++ .../Swaggers/Models/Capitalization.swift | 34 +++++++ 9 files changed, 172 insertions(+), 189 deletions(-) create mode 100644 samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift diff --git a/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache index 967dcc34735..42582ab7085 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache @@ -39,4 +39,13 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + } diff --git a/modules/swagger-codegen/src/main/resources/swift3/api.mustache b/modules/swagger-codegen/src/main/resources/swift3/api.mustache index efb24b85634..1c5b7863c09 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/api.mustache @@ -16,15 +16,6 @@ extension {{projectName}}API { {{#description}} /** {{description}} */{{/description}} open class {{classname}}: APIBase { - - public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { - return values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") - } - } - {{#operation}} {{#allParams}} {{#isEnum}} @@ -118,29 +109,35 @@ open class {{classname}}: APIBase { let URLString = {{projectName}}API.basePath + path {{#bodyParam}} let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject] + {{/bodyParam}} + {{^bodyParam}} + {{#hasFormParams}} + let formParams: [String:Any?] = [ + {{#formParams}} + {{> _param}}{{#hasMore}},{{/hasMore}} + {{/formParams}} + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + {{/hasFormParams}} + {{^hasFormParams}} + let parameters: [String:Any]? = nil + {{/hasFormParams}} + {{/bodyParam}} let url = NSURLComponents(string: URLString) {{#hasQueryParams}} - url?.queryItems = mapValuesToQueryItems(values:[ + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ {{#queryParams}} "{{paramName}}": {{paramName}}{{#hasMore}}, {{/hasMore}} {{/queryParams}} ]) {{/hasQueryParams}} - {{/bodyParam}}{{^bodyParam}} - let nillableParameters: [String:Any?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} - {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} - ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} - {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} - ]{{/hasMore}}{{/queryParams}} - - let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: {{#bodyParam}}(url?.string ?? URLString){{/bodyParam}}{{^bodyParam}}URLString{{/bodyParam}}, parameters: convertedParameters, isBody: {{hasBodyParam}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, isBody: {{hasBodyParam}}) } {{/operation}} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift index 967dcc34735..42582ab7085 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -39,4 +39,13 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { + return values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + } + } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 9f9af014045..e6bc160e271 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -10,15 +10,6 @@ import Alamofire open class FakeAPI: APIBase { - - public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { - return values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") - } - } - /** To test \"client\" model @@ -50,13 +41,10 @@ open class FakeAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -113,8 +101,7 @@ open class FakeAPI: APIBase { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -130,14 +117,15 @@ open class FakeAPI: APIBase { "password": password, "callback": callback ] - - let parameters = APIHelper.rejectNil(nillableParameters) - let convertedParameters = APIHelper.convertBoolToString(parameters) + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -209,20 +197,25 @@ open class FakeAPI: APIBase { open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ - "enum_query_string_array": enumQueryStringArray, - "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger?.encodeToJSON() + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble ] - - let parameters = APIHelper.rejectNil(nillableParameters) - let convertedParameters = APIHelper.convertBoolToString(parameters) + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enumQueryStringArray": enumQueryStringArray, + "enumQueryString": enumQueryString, + "enumQueryInteger": enumQueryInteger + ]) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 97c5ae379fe..16bc66efb60 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -10,15 +10,6 @@ import Alamofire open class PetAPI: APIBase { - - public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { - return values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") - } - } - /** Add a new pet to the store @@ -50,13 +41,10 @@ open class PetAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -88,16 +76,13 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -183,18 +168,16 @@ open class PetAPI: APIBase { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "status": status - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "status": status + ]) let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -271,18 +254,16 @@ open class PetAPI: APIBase { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "tags": tags - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "tags": tags + ]) let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -360,16 +341,13 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -403,13 +381,10 @@ open class PetAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -445,19 +420,19 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "name": name, "status": status ] - - let parameters = APIHelper.rejectNil(nillableParameters) - let convertedParameters = APIHelper.convertBoolToString(parameters) + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -498,19 +473,19 @@ open class PetAPI: APIBase { var path = "/pet/{petId}/uploadImage" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, "file": file ] - - let parameters = APIHelper.rejectNil(nillableParameters) - let convertedParameters = APIHelper.convertBoolToString(parameters) + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 08592cd4ff6..cd08a82ebdf 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -10,15 +10,6 @@ import Alamofire open class StoreAPI: APIBase { - - public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { - return values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") - } - } - /** Delete purchase order by ID @@ -45,16 +36,13 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -85,16 +73,13 @@ open class StoreAPI: APIBase { open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -153,16 +138,13 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -223,13 +205,10 @@ open class StoreAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index ffd4180c589..c15fd180ac4 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -10,15 +10,6 @@ import Alamofire open class UserAPI: APIBase { - - public class func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem] { - return values - .filter { $0.1 != nil } - .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in - URLQueryItem(name: item._key, value:"\(item._value!)") - } - } - /** Create user @@ -47,13 +38,10 @@ open class UserAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -84,13 +72,10 @@ open class UserAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -121,13 +106,10 @@ open class UserAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -156,16 +138,13 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -232,16 +211,13 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -275,19 +251,17 @@ open class UserAPI: APIBase { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "username": username, - "password": password - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, + "password": password + ]) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -312,16 +286,13 @@ open class UserAPI: APIBase { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) + let url = NSURLComponents(string: URLString) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -355,13 +326,10 @@ open class UserAPI: APIBase { let parameters = body.encodeToJSON() as? [String:AnyObject] let url = NSURLComponents(string: URLString) - - - let convertedParameters = APIHelper.convertBoolToString(parameters) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift index 2757afd722d..68190ca646c 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -254,6 +254,25 @@ class Decoders { } + // Decoder for [Capitalization] + Decoders.addDecoder(clazz: [Capitalization].self) { (source: AnyObject) -> [Capitalization] in + return Decoders.decode(clazz: [Capitalization].self, source: source) + } + // Decoder for Capitalization + Decoders.addDecoder(clazz: Capitalization.self) { (source: AnyObject) -> Capitalization in + let sourceDictionary = source as! [AnyHashable: Any] + + let instance = Capitalization() + instance.smallCamel = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["smallCamel"] as AnyObject?) + instance.capitalCamel = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["CapitalCamel"] as AnyObject?) + instance.smallSnake = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["small_Snake"] as AnyObject?) + instance.capitalSnake = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["Capital_Snake"] as AnyObject?) + instance.sCAETHFlowPoints = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["SCA_ETH_Flow_Points"] as AnyObject?) + instance.ATT_NAME = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["ATT_NAME"] as AnyObject?) + return instance + } + + // Decoder for [Cat] Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject) -> [Cat] in return Decoders.decode(clazz: [Cat].self, source: source) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 00000000000..eee1085a69c --- /dev/null +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,34 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: JSONEncodable { + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["smallCamel"] = self.smallCamel + nillableDictionary["CapitalCamel"] = self.capitalCamel + nillableDictionary["small_Snake"] = self.smallSnake + nillableDictionary["Capital_Snake"] = self.capitalSnake + nillableDictionary["SCA_ETH_Flow_Points"] = self.sCAETHFlowPoints + nillableDictionary["ATT_NAME"] = self.ATT_NAME + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} From 4001503e63f7524160f9f252830d4e2bcbbfec57 Mon Sep 17 00:00:00 2001 From: Articus Date: Sun, 15 Jan 2017 21:05:04 +0400 Subject: [PATCH 244/269] PHP server generator ze-ph (Zend Expressive + Path Handler) (#4559) * Server generator ze-ph (Zend Expressive + Path Handler) * Command line scripts for new ze-ph generator --- bin/windows/ze-ph-petstore.bat | 10 + bin/ze-ph-petstore-server.sh | 31 +++ ...endExpressivePathHandlerServerCodegen.java | 216 ++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../main/resources/ze-ph/Date.php.mustache | 17 ++ .../resources/ze-ph/DateTime.php.mustache | 44 ++++ .../ze-ph/ErrorMiddleware.php.mustache | 20 ++ .../main/resources/ze-ph/README.md.mustache | 10 + .../main/resources/ze-ph/Type.php.mustache | 71 ++++++ .../src/main/resources/ze-ph/api.mustache | 60 +++++ .../src/main/resources/ze-ph/app.yml.mustache | 19 ++ .../resources/ze-ph/composer.json.mustache | 22 ++ .../src/main/resources/ze-ph/config.yml | 2 + .../src/main/resources/ze-ph/container.php | 46 ++++ .../ze-ph/data_transfer.yml.mustache | 28 +++ .../src/main/resources/ze-ph/index.php | 10 + .../src/main/resources/ze-ph/model.mustache | 131 +++++++++++ .../resources/ze-ph/path_handler.yml.mustache | 27 +++ .../src/main/resources/ze-ph/route.mustache | 15 ++ .../petstore/ze-ph/.swagger-codegen-ignore | 23 ++ samples/server/petstore/ze-ph/README.md | 10 + .../petstore/ze-ph/application/config.yml | 2 + .../petstore/ze-ph/application/config/app.yml | 19 ++ .../application/config/data_transfer.yml | 28 +++ .../ze-ph/application/config/path_handler.yml | 131 +++++++++++ .../petstore/ze-ph/application/container.php | 46 ++++ samples/server/petstore/ze-ph/composer.json | 22 ++ .../server/petstore/ze-ph/public/index.php | 10 + .../ze-ph/src/App/DTO/ApiResponse.php | 30 +++ .../petstore/ze-ph/src/App/DTO/Category.php | 24 ++ .../petstore/ze-ph/src/App/DTO/Order.php | 50 ++++ .../server/petstore/ze-ph/src/App/DTO/Pet.php | 55 +++++ .../server/petstore/ze-ph/src/App/DTO/Tag.php | 24 ++ .../petstore/ze-ph/src/App/DTO/User.php | 61 +++++ .../ze-ph/src/App/ErrorMiddleware.php | 20 ++ .../petstore/ze-ph/src/App/Handler/Pet.php | 54 +++++ .../ze-ph/src/App/Handler/PetFindByStatus.php | 29 +++ .../ze-ph/src/App/Handler/PetFindByTags.php | 29 +++ .../ze-ph/src/App/Handler/PetPetId.php | 53 +++++ .../src/App/Handler/PetPetIdUploadImage.php | 27 +++ .../ze-ph/src/App/Handler/StoreInventory.php | 27 +++ .../ze-ph/src/App/Handler/StoreOrder.php | 32 +++ .../src/App/Handler/StoreOrderOrderId.php | 41 ++++ .../petstore/ze-ph/src/App/Handler/User.php | 31 +++ .../src/App/Handler/UserCreateWithArray.php | 31 +++ .../src/App/Handler/UserCreateWithList.php | 31 +++ .../ze-ph/src/App/Handler/UserLogin.php | 29 +++ .../ze-ph/src/App/Handler/UserLogout.php | 28 +++ .../ze-ph/src/App/Handler/UserUsername.php | 56 +++++ .../petstore/ze-ph/src/App/Strategy/Date.php | 17 ++ .../ze-ph/src/App/Strategy/DateTime.php | 44 ++++ .../petstore/ze-ph/src/App/Validator/Type.php | 71 ++++++ 52 files changed, 1965 insertions(+) create mode 100644 bin/windows/ze-ph-petstore.bat create mode 100644 bin/ze-ph-petstore-server.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/DateTime.php.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/config.yml create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/container.php create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/index.php create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/path_handler.yml.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ze-ph/route.mustache create mode 100644 samples/server/petstore/ze-ph/.swagger-codegen-ignore create mode 100644 samples/server/petstore/ze-ph/README.md create mode 100644 samples/server/petstore/ze-ph/application/config.yml create mode 100644 samples/server/petstore/ze-ph/application/config/app.yml create mode 100644 samples/server/petstore/ze-ph/application/config/data_transfer.yml create mode 100644 samples/server/petstore/ze-ph/application/config/path_handler.yml create mode 100644 samples/server/petstore/ze-ph/application/container.php create mode 100644 samples/server/petstore/ze-ph/composer.json create mode 100644 samples/server/petstore/ze-ph/public/index.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/Category.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/Order.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/Pet.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/Tag.php create mode 100644 samples/server/petstore/ze-ph/src/App/DTO/User.php create mode 100644 samples/server/petstore/ze-ph/src/App/ErrorMiddleware.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/Pet.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/PetFindByTags.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/PetPetId.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/PetPetIdUploadImage.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/StoreInventory.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/StoreOrder.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/User.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/UserLogout.php create mode 100644 samples/server/petstore/ze-ph/src/App/Handler/UserUsername.php create mode 100644 samples/server/petstore/ze-ph/src/App/Strategy/Date.php create mode 100644 samples/server/petstore/ze-ph/src/App/Strategy/DateTime.php create mode 100644 samples/server/petstore/ze-ph/src/App/Validator/Type.php diff --git a/bin/windows/ze-ph-petstore.bat b/bin/windows/ze-ph-petstore.bat new file mode 100644 index 00000000000..288870edc70 --- /dev/null +++ b/bin/windows/ze-ph-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l ze-ph -o samples\client\petstore\ze-ph + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/ze-ph-petstore-server.sh b/bin/ze-ph-petstore-server.sh new file mode 100644 index 00000000000..9289ed2f55d --- /dev/null +++ b/bin/ze-ph-petstore-server.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 -t modules/swagger-codegen/src/main/resources/ze-ph -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l ze-ph -o samples/server/petstore/ze-ph" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java new file mode 100644 index 00000000000..12328c64d58 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java @@ -0,0 +1,216 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import org.apache.commons.lang3.StringUtils; + + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ZendExpressivePathHandlerServerCodegen extends AbstractPhpCodegen { + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "ze-ph"; + } + + @Override + public String getHelp() { + return "Generates PHP server stub using Zend Expressive ( https://zendframework.github.io/zend-expressive ) and Path Handler ( https://github.com/Articus/PathHandler )."; + } + + public ZendExpressivePathHandlerServerCodegen() { + super(); + + embeddedTemplateDir = templateDir = "ze-ph"; + invokerPackage = "App"; + packagePath = ""; + srcBasePath = "src" + File.separator + "App"; + apiDirName = "Handler"; + modelDirName = "DTO"; + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; + + apiTestTemplateFiles.clear(); + modelTestTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + modelDocTemplateFiles.clear(); + + supportingFiles.add(new SupportingFile("README.md.mustache", packagePath, "README.md")); + supportingFiles.add(new SupportingFile("composer.json.mustache", packagePath, "composer.json")); + supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("container.php", packagePath + File.separator + "application", "container.php")); + supportingFiles.add(new SupportingFile("config.yml", packagePath + File.separator + "application", "config.yml")); + supportingFiles.add(new SupportingFile("app.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "app.yml")); + supportingFiles.add(new SupportingFile("path_handler.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "path_handler.yml")); + supportingFiles.add(new SupportingFile("data_transfer.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "data_transfer.yml")); + supportingFiles.add(new SupportingFile("Date.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "Date.php")); + supportingFiles.add(new SupportingFile("DateTime.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "DateTime.php")); + supportingFiles.add(new SupportingFile("Type.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Validator", "Type.php")); + supportingFiles.add(new SupportingFile("ErrorMiddleware.php.mustache", packagePath + File.separator + srcBasePath, "ErrorMiddleware.php")); + + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0"); + } + + /** + * Add operation to group + * Override of default grouping - group by resource path, not tag + * + * @param tag name of the tag + * @param resourcePath path of the resource + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations + */ + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + List opList = operations.get(resourcePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(resourcePath, opList); + } + //ignore duplicate operation ids - that means that operation has several tags + int counter = 0; + for (CodegenOperation op : opList) { + if (co.operationId.equals(op.operationId)) { + counter++; + } + } + if (counter == 0) { + co.operationIdLowerCase = co.operationId.toLowerCase(); + opList.add(co); + co.baseName = tag; + } + } + + /** + * Return the file name of the Api Test + * + * @param name the file name of the Api + * @return the file name of the Api + */ + @Override + public String toApiFilename(String name) { + return toApiName(name); + } + + /** + * Output the API (class) name (capitalized) ending with "Api" + * Return DefaultApi if name is empty + * + * @param name the name of the Api + * @return capitalized Api name ending with "Api" + */ + @Override + public String toApiName(String name) { + //Remove } + name = name.replaceAll("[\\}]", ""); + return super.toModelName(name); + } + + @Override + public Map postProcessOperations(Map objs) { + objs = super.postProcessOperations(objs); + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + String interfaceToImplement; + StringBuilder interfacesToImplement = new StringBuilder(); + String classMethod; + for (CodegenOperation op : operationList) { + switch (op.httpMethod) { + case "GET": + interfaceToImplement = "Operation\\GetInterface"; + classMethod = "handleGet"; + break; + case "POST": + interfaceToImplement = "Operation\\PostInterface"; + classMethod = "handlePost"; + break; + case "PATCH": + interfaceToImplement = "Operation\\PatchInterface"; + classMethod = "handlePatch"; + break; + case "PUT": + interfaceToImplement = "Operation\\PutInterface"; + classMethod = "handlePut"; + break; + case "DELETE": + interfaceToImplement = "Operation\\DeleteInterface"; + classMethod = "handleDelete"; + break; + default: + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + } + if (interfacesToImplement.length() > 0) { + interfacesToImplement.append(", "); + } + interfacesToImplement.append(interfaceToImplement); + op.httpMethod = classMethod; + } + operations.put("interfacesToImplement", interfacesToImplement.toString()); + + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + objs = super.postProcessSupportingFileData(objs); + + Map apiInfo = (Map) objs.get("apiInfo"); + List> apis = (List>) apiInfo.get("apis"); + + List> routes = new ArrayList>(); + for (Map api : apis) { + String handler = (String) api.get("classname"); + String url = (String) api.get("baseName"); + if (url.charAt(0) == '/') { + url = url.substring(1); + } + insertRoute(routes, url.split("/"), 0, handler); + } + + objs.put("routes", routes); + return objs; + } + + private void insertRoute(List> routes, String[] urlParts, int currentUrlPartIndex, String handler) { + if (urlParts.length > currentUrlPartIndex) { + String urlPart = urlParts[currentUrlPartIndex]; + //List> subRoutes = null; + Map currentRoute = null; + for (Map route : routes) { + if (urlPart.equals(route.get("name"))) { + currentRoute = route; + break; + } + } + if (currentRoute == null) { + currentRoute = new HashMap(); + + String routePart = urlPart.replaceAll("^\\{(\\w+)\\}$", ":$1"); + boolean isLastUrlPart = currentUrlPartIndex == urlParts.length - 1; + + currentRoute.put("name", urlPart); + currentRoute.put("route", "/" + routePart); + currentRoute.put("type", (urlPart == routePart) ? "Literal" : "Segment"); + currentRoute.put("handler", isLastUrlPart ? handler : null); + currentRoute.put("hasChildren", false); + currentRoute.put("children", new ArrayList>()); + currentRoute.put("padding", StringUtils.repeat(' ', 4 * currentUrlPartIndex)); + + routes.add(currentRoute); + } + List> subRoutes = (List>) currentRoute.get("children"); + insertRoute(subRoutes, urlParts, currentUrlPartIndex + 1, handler); + currentRoute.put("hasChildren", !subRoutes.isEmpty()); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 9b36d8c527a..8da47e907a3 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -59,3 +59,4 @@ io.swagger.codegen.languages.GoServerCodegen io.swagger.codegen.languages.ErlangServerCodegen io.swagger.codegen.languages.UndertowCodegen io.swagger.codegen.languages.JavaMSF4JServerCodegen +io.swagger.codegen.languages.ZendExpressivePathHandlerServerCodegen \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache new file mode 100644 index 00000000000..89bcf5ba0ec --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache @@ -0,0 +1,17 @@ +format(static::DATE_TIME_FORMAT); + } + return $result; + } + + /** + * @inheritDoc + */ + public function hydrate($arrayValue, $objectValue, array $array = null) + { + $result = null; + if (!empty($arrayValue)) { + $date = $this->parseDateString($arrayValue); + if ($date instanceof \DateTime) { + $result = $date; + } + } + return $result; + } + + /** + * @param $arrayValue + * @return \DateTime + */ + protected function parseDateString($arrayValue) + { + return \DateTime::createFromFormat(static::DATE_TIME_FORMAT, $arrayValue, new \DateTimeZone('UTC')); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache new file mode 100644 index 00000000000..d9696c081c9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache @@ -0,0 +1,20 @@ +withStatus(500, 'Internal server error'); + $response->getBody()->write((string)$error); + error_log((string) $error); + return ($out === null)? $response : $out($request, $response); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache new file mode 100644 index 00000000000..81eb543af3a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Zend Expressive](https://zendframework.github.io/zend-expressive) micro framework and [Path Handler](https://github.com/Articus/PathHandler) library. To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/ze-ph/) diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache new file mode 100644 index 00000000000..050fbbef54b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache @@ -0,0 +1,71 @@ + 'Invalid type given.', + ]; + + /** + * @var string + */ + protected $type; + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * @return self + */ + public function setType($type) + { + $this->type = $type; + return $this; + } + + /** + * @inheritDoc + */ + public function isValid($value) + { + $result = true; + if (!$this->checkType($value)) { + $this->error(self::INVALID); + $result = false; + } + return $result; + } + + protected function checkType($value) + { + switch ($this->type) { + case 'int': + return is_int($value); + case 'bool': + return is_bool($value); + case 'float': + return is_float($value) || is_int($value); + case 'string': + return is_string($value); + default: + throw new \InvalidArgumentException(sprintf('Can not check for type %s.', $this->type)); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache new file mode 100644 index 00000000000..a2463ccfb65 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache @@ -0,0 +1,60 @@ +getAttribute("{{paramName}}"); +{{/isPrimitiveType}} +{{/bodyParam}} + throw new PHException\HttpCode(500, "Not implemented"); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache new file mode 100644 index 00000000000..1cabd291fd6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache @@ -0,0 +1,19 @@ +dependencies: + invokables: + #Has to add this line because currently router is strict requirement for Zend\Expressive\Application even if only middleware_pipeline is used + Zend\Expressive\Router\RouterInterface: Zend\Expressive\Router\ZendRouter + Zend\Diactoros\Response\EmitterInterface: Zend\Diactoros\Response\SapiStreamEmitter + {{invokerPackage}}\ErrorMiddleware: {{invokerPackage}}\ErrorMiddleware + factories: + Zend\Expressive\Application: Zend\Expressive\Container\ApplicationFactory + Articus\PathHandler\Middleware: Articus\PathHandler\MiddlewareFactory + Articus\DataTransfer\Service: Articus\DataTransfer\ServiceFactory + +middleware_pipeline: + api: + middleware: Articus\PathHandler\Middleware + path: {{basePathWithoutHost}} + error: + middleware: {{invokerPackage}}\ErrorMiddleware + error: true + priority: -10000 diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache new file mode 100644 index 00000000000..df263a37b8e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache @@ -0,0 +1,22 @@ +{ + "name": "{{gitUserId}}/{{gitRepoId}}", + "description": "{{description}}", + "license": "proprietary", + "version": "{{artifactVersion}}", + "type": "project", + "require": { + "php": "^5.6 || ^7.0", + "ext-yaml" : "^1.2 || ^2.0", + "zendframework/zend-expressive": "^1.0", + "zendframework/zend-expressive-router": "1.2.*", + "articus/path-handler": "0.1.*", + "articus/data-transfer": "*", + "zendframework/zend-serializer": "*", + "zendframework/zend-config": "*" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/config.yml b/modules/swagger-codegen/src/main/resources/ze-ph/config.yml new file mode 100644 index 00000000000..dce9c534bcd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/config.yml @@ -0,0 +1,2 @@ +#App +cache_configuration: false diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/container.php b/modules/swagger-codegen/src/main/resources/ze-ph/container.php new file mode 100644 index 00000000000..e70a0663cf3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/container.php @@ -0,0 +1,46 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache new file mode 100644 index 00000000000..8c9fb5bfceb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache @@ -0,0 +1,28 @@ +data_transfer: + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/data_transfer +# namespace: dt + + strategies: + invokables: + {{invokerPackage}}\Strategy\Date: {{invokerPackage}}\Strategy\Date + {{invokerPackage}}\Strategy\DateTime: {{invokerPackage}}\Strategy\DateTime +# factories: + aliases: + Date: {{invokerPackage}}\Strategy\Date + DateTime: {{invokerPackage}}\Strategy\DateTime + validators: + invokables: + {{invokerPackage}}\Validator\Type: {{invokerPackage}}\Validator\Type + factories: + Articus\DataTransfer\Validator\Dictionary: Articus\DataTransfer\Validator\Factory + Articus\DataTransfer\Validator\Collection: Articus\DataTransfer\Validator\Factory + aliases: + Dictionary: Articus\DataTransfer\Validator\Dictionary + Collection: Articus\DataTransfer\Validator\Collection + Type: {{invokerPackage}}\Validator\Type diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/index.php b/modules/swagger-codegen/src/main/resources/ze-ph/index.php new file mode 100644 index 00000000000..09e8b0233e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/index.php @@ -0,0 +1,10 @@ +get(\Zend\Expressive\Application::class); +$app->run(); \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache new file mode 100644 index 00000000000..69201b27e5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache @@ -0,0 +1,131 @@ +route}}{{/routes}} + default_params: + middleware: '' + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/path_handler +# namespace: ph + + handlers: + invokables: +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{classname}}: {{package}}\{{classname}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +# consumers: +# attributes: +# producers: diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache new file mode 100644 index 00000000000..cfb73260540 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache @@ -0,0 +1,15 @@ + {{padding}}'{{name}}': + {{padding}} type: {{type}} + {{padding}} options: + {{padding}} route: {{route}} +{{#handler}} + {{padding}} defaults: + {{padding}} handler: {{handler}} +{{/handler}} +{{#hasChildren}} +{{#handler}} + {{padding}} may_terminate: true +{{/handler}} + {{padding}} child_routes: +{{/hasChildren}} +{{#children}}{{>route}}{{/children}} \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/.swagger-codegen-ignore b/samples/server/petstore/ze-ph/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/ze-ph/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/ze-ph/README.md b/samples/server/petstore/ze-ph/README.md new file mode 100644 index 00000000000..81eb543af3a --- /dev/null +++ b/samples/server/petstore/ze-ph/README.md @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Zend Expressive](https://zendframework.github.io/zend-expressive) micro framework and [Path Handler](https://github.com/Articus/PathHandler) library. To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/ze-ph/) diff --git a/samples/server/petstore/ze-ph/application/config.yml b/samples/server/petstore/ze-ph/application/config.yml new file mode 100644 index 00000000000..dce9c534bcd --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config.yml @@ -0,0 +1,2 @@ +#App +cache_configuration: false diff --git a/samples/server/petstore/ze-ph/application/config/app.yml b/samples/server/petstore/ze-ph/application/config/app.yml new file mode 100644 index 00000000000..d91bcd21339 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/app.yml @@ -0,0 +1,19 @@ +dependencies: + invokables: + #Has to add this line because currently router is strict requirement for Zend\Expressive\Application even if only middleware_pipeline is used + Zend\Expressive\Router\RouterInterface: Zend\Expressive\Router\ZendRouter + Zend\Diactoros\Response\EmitterInterface: Zend\Diactoros\Response\SapiStreamEmitter + App\ErrorMiddleware: App\ErrorMiddleware + factories: + Zend\Expressive\Application: Zend\Expressive\Container\ApplicationFactory + Articus\PathHandler\Middleware: Articus\PathHandler\MiddlewareFactory + Articus\DataTransfer\Service: Articus\DataTransfer\ServiceFactory + +middleware_pipeline: + api: + middleware: Articus\PathHandler\Middleware + path: /v2 + error: + middleware: App\ErrorMiddleware + error: true + priority: -10000 diff --git a/samples/server/petstore/ze-ph/application/config/data_transfer.yml b/samples/server/petstore/ze-ph/application/config/data_transfer.yml new file mode 100644 index 00000000000..6040af29208 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/data_transfer.yml @@ -0,0 +1,28 @@ +data_transfer: + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/data_transfer +# namespace: dt + + strategies: + invokables: + App\Strategy\Date: App\Strategy\Date + App\Strategy\DateTime: App\Strategy\DateTime +# factories: + aliases: + Date: App\Strategy\Date + DateTime: App\Strategy\DateTime + validators: + invokables: + App\Validator\Type: App\Validator\Type + factories: + Articus\DataTransfer\Validator\Dictionary: Articus\DataTransfer\Validator\Factory + Articus\DataTransfer\Validator\Collection: Articus\DataTransfer\Validator\Factory + aliases: + Dictionary: Articus\DataTransfer\Validator\Dictionary + Collection: Articus\DataTransfer\Validator\Collection + Type: App\Validator\Type diff --git a/samples/server/petstore/ze-ph/application/config/path_handler.yml b/samples/server/petstore/ze-ph/application/config/path_handler.yml new file mode 100644 index 00000000000..39048ff6f48 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/path_handler.yml @@ -0,0 +1,131 @@ +path_handler: + routes: + routes: + 'pet': + type: Literal + options: + route: /pet + defaults: + handler: Pet + may_terminate: true + child_routes: + 'findByStatus': + type: Literal + options: + route: /findByStatus + defaults: + handler: PetFindByStatus + 'findByTags': + type: Literal + options: + route: /findByTags + defaults: + handler: PetFindByTags + '{petId}': + type: Segment + options: + route: /:petId + defaults: + handler: PetPetId + may_terminate: true + child_routes: + 'uploadImage': + type: Literal + options: + route: /uploadImage + defaults: + handler: PetPetIdUploadImage + 'store': + type: Literal + options: + route: /store + child_routes: + 'inventory': + type: Literal + options: + route: /inventory + defaults: + handler: StoreInventory + 'order': + type: Literal + options: + route: /order + defaults: + handler: StoreOrder + may_terminate: true + child_routes: + '{orderId}': + type: Segment + options: + route: /:orderId + defaults: + handler: StoreOrderOrderId + 'user': + type: Literal + options: + route: /user + defaults: + handler: User + may_terminate: true + child_routes: + 'createWithArray': + type: Literal + options: + route: /createWithArray + defaults: + handler: UserCreateWithArray + 'createWithList': + type: Literal + options: + route: /createWithList + defaults: + handler: UserCreateWithList + 'login': + type: Literal + options: + route: /login + defaults: + handler: UserLogin + 'logout': + type: Literal + options: + route: /logout + defaults: + handler: UserLogout + '{username}': + type: Segment + options: + route: /:username + defaults: + handler: UserUsername + + default_params: + middleware: '' + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/path_handler +# namespace: ph + + handlers: + invokables: + Pet: App\Handler\Pet + PetFindByStatus: App\Handler\PetFindByStatus + PetFindByTags: App\Handler\PetFindByTags + PetPetId: App\Handler\PetPetId + PetPetIdUploadImage: App\Handler\PetPetIdUploadImage + StoreInventory: App\Handler\StoreInventory + StoreOrder: App\Handler\StoreOrder + StoreOrderOrderId: App\Handler\StoreOrderOrderId + User: App\Handler\User + UserCreateWithArray: App\Handler\UserCreateWithArray + UserCreateWithList: App\Handler\UserCreateWithList + UserLogin: App\Handler\UserLogin + UserLogout: App\Handler\UserLogout + UserUsername: App\Handler\UserUsername +# consumers: +# attributes: +# producers: diff --git a/samples/server/petstore/ze-ph/application/container.php b/samples/server/petstore/ze-ph/application/container.php new file mode 100644 index 00000000000..e70a0663cf3 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/container.php @@ -0,0 +1,46 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/samples/server/petstore/ze-ph/composer.json b/samples/server/petstore/ze-ph/composer.json new file mode 100644 index 00000000000..5cad52b27e2 --- /dev/null +++ b/samples/server/petstore/ze-ph/composer.json @@ -0,0 +1,22 @@ +{ + "name": "GIT_USER_ID/GIT_REPO_ID", + "description": "", + "license": "proprietary", + "version": "1.0.0", + "type": "project", + "require": { + "php": "^5.6 || ^7.0", + "ext-yaml" : "^1.2 || ^2.0", + "zendframework/zend-expressive": "^1.0", + "zendframework/zend-expressive-router": "1.2.*", + "articus/path-handler": "0.1.*", + "articus/data-transfer": "*", + "zendframework/zend-serializer": "*", + "zendframework/zend-config": "*" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} diff --git a/samples/server/petstore/ze-ph/public/index.php b/samples/server/petstore/ze-ph/public/index.php new file mode 100644 index 00000000000..09e8b0233e4 --- /dev/null +++ b/samples/server/petstore/ze-ph/public/index.php @@ -0,0 +1,10 @@ +get(\Zend\Expressive\Application::class); +$app->run(); \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php b/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php new file mode 100644 index 00000000000..9d978986b06 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php @@ -0,0 +1,30 @@ +withStatus(500, 'Internal server error'); + $response->getBody()->write((string)$error); + error_log((string) $error); + return ($out === null)? $response : $out($request, $response); + } +} \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/Handler/Pet.php b/samples/server/petstore/ze-ph/src/App/Handler/Pet.php new file mode 100644 index 00000000000..035e9b19b83 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/Pet.php @@ -0,0 +1,54 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } + /** + * Update an existing pet + * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + * @PHA\Consumer(name=PHConsumer\Json::class, mediaType="application/json") + * TODO check if consumer is valid, if it has correct priority and if it can be moved to class annotation + * @PHA\Consumer(name=PHConsumer\Json::class, mediaType="application/xml") + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Pet::class,"objectAttr":"body"}) + * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/xml") + * TODO check if producer is valid, if it has correct priority and if it can be moved to class annotation + * @PHA\Producer(name=PHProducer\Transfer::class, mediaType="application/json") + */ + public function handlePut(ServerRequestInterface $request) + { + //TODO implement method + /** @var \App\DTO\Pet $body */ + $body = $request->getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php new file mode 100644 index 00000000000..3c9ae5149cc --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php @@ -0,0 +1,29 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php b/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php new file mode 100644 index 00000000000..4bb3c7e8444 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php @@ -0,0 +1,41 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php new file mode 100644 index 00000000000..cc0f119db3f --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php @@ -0,0 +1,31 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php new file mode 100644 index 00000000000..7cd3e2cc649 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php @@ -0,0 +1,31 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php b/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php new file mode 100644 index 00000000000..657218c99e8 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php @@ -0,0 +1,29 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Strategy/Date.php b/samples/server/petstore/ze-ph/src/App/Strategy/Date.php new file mode 100644 index 00000000000..91c83c363a8 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Strategy/Date.php @@ -0,0 +1,17 @@ +format(static::DATE_TIME_FORMAT); + } + return $result; + } + + /** + * @inheritDoc + */ + public function hydrate($arrayValue, $objectValue, array $array = null) + { + $result = null; + if (!empty($arrayValue)) { + $date = $this->parseDateString($arrayValue); + if ($date instanceof \DateTime) { + $result = $date; + } + } + return $result; + } + + /** + * @param $arrayValue + * @return \DateTime + */ + protected function parseDateString($arrayValue) + { + return \DateTime::createFromFormat(static::DATE_TIME_FORMAT, $arrayValue, new \DateTimeZone('UTC')); + } +} \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/Validator/Type.php b/samples/server/petstore/ze-ph/src/App/Validator/Type.php new file mode 100644 index 00000000000..79644bacf06 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Validator/Type.php @@ -0,0 +1,71 @@ + 'Invalid type given.', + ]; + + /** + * @var string + */ + protected $type; + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * @return self + */ + public function setType($type) + { + $this->type = $type; + return $this; + } + + /** + * @inheritDoc + */ + public function isValid($value) + { + $result = true; + if (!$this->checkType($value)) { + $this->error(self::INVALID); + $result = false; + } + return $result; + } + + protected function checkType($value) + { + switch ($this->type) { + case 'int': + return is_int($value); + case 'bool': + return is_bool($value); + case 'float': + return is_float($value) || is_int($value); + case 'string': + return is_string($value); + default: + throw new \InvalidArgumentException(sprintf('Can not check for type %s.', $this->type)); + } + } +} \ No newline at end of file From 2d8715f42c9152c36f8af3e3b3a45bd963b14300 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 01:10:35 +0800 Subject: [PATCH 245/269] Minor update to ze-ph batch script - use petstore-with-fake-endpoints-models-for-testing.yaml - output to samples\server\petstore\ze-ph --- bin/windows/ze-ph-petstore.bat | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/windows/ze-ph-petstore.bat b/bin/windows/ze-ph-petstore.bat index 288870edc70..a25de587857 100644 --- a/bin/windows/ze-ph-petstore.bat +++ b/bin/windows/ze-ph-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l ze-ph -o samples\client\petstore\ze-ph +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l ze-ph -o samples\server\petstore\ze-ph java %JAVA_OPTS% -jar %executable% %ags% From 23c5376ed66058b85e4b5768de901e8195a2799c Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 15 Jan 2017 11:12:03 -0600 Subject: [PATCH 246/269] [csharp] Fix interfacePrefix sensitivity + default (#4561) After merging the fix with another C# change, noticed case sensitivity issue for the true/false checks. Also noticed my original implementation wasn't setting the default I- prefix as intended. This commit resolves those three issues. --- .../swagger/codegen/languages/AbstractCSharpCodegen.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 746edebc9ca..10ccff345c1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -259,15 +259,16 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); - if("false".equals(useInterfacePrefix)) { + if("false".equals(useInterfacePrefix.toLowerCase())) { setInterfacePrefix(""); - } else if(!"true".equals(useInterfacePrefix)) { + } else if(!"true".equals(useInterfacePrefix.toLowerCase())) { // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. setInterfacePrefix(sanitizeName(useInterfacePrefix)); } - - additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); } + + // This either updates additionalProperties with the above fixes, or sets the default if the option was not specified. + additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); } @Override From d97b1da90c75caf0c4814a8393340754c394495d Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Sun, 15 Jan 2017 11:19:10 -0600 Subject: [PATCH 247/269] [csharp] Support internal access of generated code (#4560) Allows users to specify 'nonPublicApi' additional property (and C# client CLI switch) to reduce visibility of classes created by the generator. This includes API and Models as well as supporting code like ApiClient and other infrastructure. The requirement is to support codegen generated code to be embedded within other applications where the generated code is not intended to be publicly consumable or publicy exposed. An example would be an SDK which internally consumes an API via the generated code; we wouldn't want the internal API implementation exposed as part of that SDK. Reducing visibility of the classes effectively makes the entire implementation internal, regardless of the public modifier on methods or static members. To fully make all members internal it would require explicit interface implementation, which is not ideal. see #4401 --- .../io/swagger/codegen/CodegenConstants.java | 3 +++ .../languages/CSharpClientCodegen.java | 23 +++++++++++++++++++ .../main/resources/csharp/ApiClient.mustache | 2 +- .../resources/csharp/ApiException.mustache | 2 +- .../resources/csharp/ApiResponse.mustache | 2 +- .../resources/csharp/Configuration.mustache | 2 +- .../csharp/ExceptionFactory.mustache | 4 ++-- .../resources/csharp/IApiAccessor.mustache | 2 +- .../src/main/resources/csharp/api.mustache | 4 ++-- .../main/resources/csharp/enumClass.mustache | 2 +- .../main/resources/csharp/modelEnum.mustache | 2 +- .../resources/csharp/modelGeneric.mustache | 2 +- .../resources/csharp/modelInnerEnum.mustache | 2 +- .../main/resources/csharp/visibility.mustache | 1 + .../csharp/CSharpClientOptionsTest.java | 2 ++ .../options/CSharpClientOptionsProvider.java | 1 + 16 files changed, 43 insertions(+), 13 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/csharp/visibility.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index f5c759d4d04..aacb5f2737e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -144,4 +144,7 @@ public class CodegenConstants { public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged"; public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; + + public static final String NON_PUBLIC_API = "nonPublicApi"; + public static final String NON_PUBLIC_API_DESC = "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers."; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index cf4bc656d83..526fffeda18 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -45,6 +45,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected Map regexModifiers; protected final Map frameworks; + // By default, generated code is considered public + protected boolean nonPublicApi = Boolean.FALSE; + public CSharpClientCodegen() { super(); modelTemplateFiles.put("model.mustache", ".cs"); @@ -130,6 +133,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { CodegenConstants.PACKAGE_DESCRIPTION_DESC, this.generatePropertyChanged); + // NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo + // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx + // to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen + // should rely on default public visibility. + addSwitch(CodegenConstants.NON_PUBLIC_API, + CodegenConstants.NON_PUBLIC_API_DESC, + this.nonPublicApi); + regexModifiers = new HashMap(); regexModifiers.put('i', "IgnoreCase"); regexModifiers.put('m', "Multiline"); @@ -232,6 +243,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); } + if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) { + setNonPublicApi(Boolean.valueOf(additionalProperties.get(CodegenConstants.NON_PUBLIC_API).toString())); + } + final String testPackageName = testPackageName(); String packageFolder = sourceFolder + File.separator + packageName; String clientPackageDir = packageFolder + File.separator + clientPackage; @@ -555,6 +570,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { this.generatePropertyChanged = generatePropertyChanged; } + public boolean isNonPublicApi() { + return nonPublicApi; + } + + public void setNonPublicApi(final boolean nonPublicApi) { + this.nonPublicApi = nonPublicApi; + } + @Override public String toModelDocFilename(String name) { return toModelFilename(name); diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 33b631280c2..8960ccfe59e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -19,7 +19,7 @@ namespace {{packageName}}.Client /// /// API client is mainly responsible for making the HTTP call to the API backend. /// - public partial class ApiClient + {{>visibility}} partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index ad7c2264d78..ca8044580f2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -6,7 +6,7 @@ namespace {{packageName}}.Client /// /// API Exception /// - public class ApiException : Exception + {{>visibility}} class ApiException : Exception { /// /// Gets or sets the error code (HTTP status code) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index d8c1b79e545..d04575d7ad9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -7,7 +7,7 @@ namespace {{packageName}}.Client /// /// API Response /// - public class ApiResponse + {{>visibility}} class ApiResponse { /// /// Gets or sets the status code (HTTP status code) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 108b85e48f8..0e1856725df 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -11,7 +11,7 @@ namespace {{packageName}}.Client /// /// Represents a set of configuration settings /// - public class Configuration + {{>visibility}} class Configuration { /// /// Initializes a new instance of the Configuration class with different settings diff --git a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache index c25b88ee614..f0ebb0b31ce 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache @@ -10,6 +10,6 @@ namespace {{packageName}}.Client /// /// Method name /// Response - /// Exceptions - public delegate Exception ExceptionFactory(string methodName, IRestResponse response); + /// Exceptions + {{>visibility}} delegate Exception ExceptionFactory(string methodName, IRestResponse response); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache index df236b8f8c8..290c9b6ffdc 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -11,7 +11,7 @@ namespace {{packageName}}.Client /// /// Represents configuration aspects required to interact with the API endpoints. /// - public interface IApiAccessor + {{>visibility}} interface IApiAccessor { /// /// Gets or sets the configuration object diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 18c949980cb..c3d73306149 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -14,7 +14,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public interface {{interfacePrefix}}{{classname}} : IApiAccessor + {{>visibility}} interface {{interfacePrefix}}{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} @@ -73,7 +73,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class {{classname}} : {{interfacePrefix}}{{classname}} + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} { private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; diff --git a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache index 5249d754577..b11d14cdfc0 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache @@ -3,7 +3,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache index ff007904f46..b0dfa881eb2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache @@ -3,7 +3,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 5e1d0721dc2..09c232acefd 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -5,7 +5,7 @@ {{#generatePropertyChanged}} [ImplementPropertyChanged] {{/generatePropertyChanged}} - public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>, IValidatableObject + {{>visibility}} partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>, IValidatableObject { {{#vars}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache index 855a710c7ed..d851a2dddc6 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache @@ -4,7 +4,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache b/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache new file mode 100644 index 00000000000..a1d1f4163d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 8bc55f211be..195d928d8c6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -50,6 +50,8 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGeneratePropertyChanged(true); times = 1; + clientCodegen.setNonPublicApi(true); + times = 1; clientCodegen.setInterfacePrefix("X"); times = 1; }}; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 9bbc6512911..833184775ba 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -35,6 +35,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.GENERATE_PROPERTY_CHANGED, "true") + .put(CodegenConstants.NON_PUBLIC_API, "true") .put(CodegenConstants.INTERFACE_PREFIX, "X") .build(); } From 0ea506e970f81e22687d999c1a49957567ec7856 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 13:22:53 +0800 Subject: [PATCH 248/269] Add http://htc-cs.com --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f260d4dec42..72db16821f3 100644 --- a/README.md +++ b/README.md @@ -789,6 +789,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [goTransverse](http://www.gotransverse.com/api) - [GraphHopper](https://graphhopper.com/) - [Gravitate Solutions](http://gravitatesolutions.com/) +- [High Technologies Center](http://htc-cs.com) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Intent HQ](http://www.intenthq.com) - [Interactive Intelligence](http://developer.mypurecloud.com/) From 410f6d74c81b123d2685fc42339b55df38d68931 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 16:16:14 +0800 Subject: [PATCH 249/269] add Articus as php expressive creator --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 72db16821f3..20f160cdc3c 100644 --- a/README.md +++ b/README.md @@ -929,6 +929,7 @@ Here is a list of template creators: * JAX-RS CXF (CDI): @nickcmaynard * PHP Lumen: @abcsum * PHP Slim: @jfastnacht + * PHP Zend Expressive (with Path Handler): @Articus * Ruby on Rails 5: @zlx * Documentation * HTML Doc 2: @jhitchcock From 3b3ded0290b1054df22cefd8225fe0c5568cb37c Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 19:09:25 +0800 Subject: [PATCH 250/269] fix bash test package name (#4566) --- .../src/test/java/io/swagger/codegen/bash/BashTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java index a59b083201a..4f355723a7f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java @@ -1,4 +1,4 @@ -package io.swagger.codegen.python; +package io.swagger.codegen.bash; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; From 033a588c758c7b1da633d65e3cfc1b5f08cf3b6c Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 22:12:12 +0800 Subject: [PATCH 251/269] add zend expressive --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 20f160cdc3c..fd3ecdf3d64 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: - **API clients**: **ActionScript**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) -- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) +- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex, Zend Expressivea), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** From 691d89adeb932f137a79862a39a468675ac8c3a7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 16 Jan 2017 22:13:31 +0800 Subject: [PATCH 252/269] add link to zend-expressive --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fd3ecdf3d64..544c7c226f4 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: - **API clients**: **ActionScript**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) -- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex, Zend Expressivea), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) +- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex, [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** From 713e6bba249983995ab7b821ffc95c4fb8d8ff59 Mon Sep 17 00:00:00 2001 From: Brian Shamblen Date: Mon, 16 Jan 2017 18:35:55 -0800 Subject: [PATCH 253/269] [html2] Add python and perl examples (#4575) Fixes #4358 --- .../io/swagger/codegen/CodegenConstants.java | 6 + .../languages/StaticHtml2Generator.java | 6 + .../main/resources/htmlDocs2/index.mustache | 10 + .../resources/htmlDocs2/sample_perl.mustache | 26 + .../htmlDocs2/sample_python.mustache | 28 + samples/html2/index.html | 818 +++++++++++++++++- 6 files changed, 890 insertions(+), 4 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index aacb5f2737e..89a8666d93d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -19,6 +19,12 @@ public class CodegenConstants { public static final String PHP_INVOKER_PACKAGE = "phpInvokerPackage"; public static final String PHP_INVOKER_PACKAGE_DESC = "root package for generated php code"; + public static final String PERL_MODULE_NAME = "perlModuleName"; + public static final String PERL_MODULE_NAME_DESC = "root module name for generated perl code"; + + public static final String PYTHON_PACKAGE_NAME = "pythonPackageName"; + public static final String PYTHON_PACKAGE_NAME_DESC = "package name for generated python code"; + public static final String GROUP_ID = "groupId"; public static final String GROUP_ID_DESC = "groupId in generated pom.xml"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 7a07ef8a58f..06c23075e8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -24,6 +24,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi protected String artifactVersion = "1.0.0"; protected String jsProjectName; protected String jsModuleName; + protected String perlModuleName = "WWW::SwaggerClient"; + protected String pythonPackageName = "swagger_client"; public StaticHtml2Generator() { super(); @@ -40,6 +42,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PERL_MODULE_NAME, CodegenConstants.PERL_MODULE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PYTHON_PACKAGE_NAME, CodegenConstants.PYTHON_PACKAGE_NAME_DESC)); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); @@ -53,6 +57,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.PHP_INVOKER_PACKAGE, phpInvokerPackage); + additionalProperties.put(CodegenConstants.PERL_MODULE_NAME, perlModuleName); + additionalProperties.put(CodegenConstants.PYTHON_PACKAGE_NAME, pythonPackageName); additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index a6b8ad90c7a..01f9f2eb720 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -218,6 +218,8 @@
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -253,6 +255,14 @@
    {{>sample_php}}
    + +
    +
    {{>sample_perl}}
    +
    + +
    +
    {{>sample_python}}
    +

    Parameters

    diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache new file mode 100644 index 00000000000..413c3df4426 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache @@ -0,0 +1,26 @@ +use Data::Dumper; +use {{{perlModuleName}}}::Configuration; +use {{perlModuleName}}::{{classname}}; +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::username = 'YOUR_USERNAME'; +${{{perlModuleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#${{{perlModuleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = "Bearer";{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +my $api_instance = {{perlModuleName}}::{{classname}}->new(); +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{perlModuleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{description}}} +{{/allParams}} + +eval { + {{#returnType}}my $result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print Dumper($result);{{/returnType}} +}; +if ($@) { + warn "Exception when calling {{classname}}->{{operationId}}: $@\n"; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache new file mode 100644 index 00000000000..1860823d4e0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache @@ -0,0 +1,28 @@ +from __future__ import print_statement +import time +import {{{pythonPackageName}}} +from {{{pythonPackageName}}}.rest import ApiException +from pprint import pprint +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.username = 'YOUR_USERNAME' +{{{pythonPackageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# {{{pythonPackageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +# create an instance of the API class +api_instance = {{{pythonPackageName}}}.{{{classname}}}() +{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +try: +{{#summary}} # {{{.}}} +{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} + pprint(api_response){{/returnType}} +except ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) \ No newline at end of file diff --git a/samples/html2/index.html b/samples/html2/index.html index ef49082d8d7..2265d5f2811 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -1006,6 +1006,8 @@ margin-bottom: 20px;
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1161,6 +1163,46 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store
    +
    +eval { 
    +    $api_instance->addPet(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->addPet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +body =  # Pet | Pet object that needs to be added to the store
    +
    +try: 
    +    # Add a new pet to the store
    +    api_instance.addPet(body)
    +except ApiException as e:
    +    print("Exception when calling PetApi->addPet: %s\n" % e)
    +

    Parameters

    @@ -1253,6 +1295,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1417,6 +1461,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | Pet id to delete
    +my $apiKey = apiKey_example; # String | 
    +
    +eval { 
    +    $api_instance->deletePet(petId => $petId, apiKey => $apiKey);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->deletePet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | Pet id to delete
    +apiKey = apiKey_example # String |  (optional)
    +
    +try: 
    +    # Deletes a pet
    +    api_instance.deletePet(petId, apiKey=apiKey)
    +except ApiException as e:
    +    print("Exception when calling PetApi->deletePet: %s\n" % e)
    +

    Parameters

    @@ -1538,6 +1624,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1700,6 +1788,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $status = []; # array[String] | Status values that need to be considered for filter
    +
    +eval { 
    +    my $result = $api_instance->findPetsByStatus(status => $status);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->findPetsByStatus: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +status =  # array[String] | Status values that need to be considered for filter
    +
    +try: 
    +    # Finds Pets by status
    +    api_response = api_instance.findPetsByStatus(status)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->findPetsByStatus: %s\n" % e)
    +

    Parameters

    @@ -1832,6 +1962,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1994,6 +2126,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $tags = []; # array[String] | Tags to filter by
    +
    +eval { 
    +    my $result = $api_instance->findPetsByTags(tags => $tags);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->findPetsByTags: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +tags =  # array[String] | Tags to filter by
    +
    +try: 
    +    # Finds Pets by tags
    +    api_response = api_instance.findPetsByTags(tags)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->findPetsByTags: %s\n" % e)
    +

    Parameters

    @@ -2124,6 +2298,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -2296,6 +2472,52 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure API key authorization: api_key
    +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
    +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet to return
    +
    +eval { 
    +    my $result = $api_instance->getPetById(petId => $petId);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->getPetById: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure API key authorization: api_key
    +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
    +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | ID of pet to return
    +
    +try: 
    +    # Find pet by ID
    +    api_response = api_instance.getPetById(petId)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->getPetById: %s\n" % e)
    +

    Parameters

    @@ -2422,6 +2644,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -2577,6 +2801,46 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store
    +
    +eval { 
    +    $api_instance->updatePet(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->updatePet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +body =  # Pet | Pet object that needs to be added to the store
    +
    +try: 
    +    # Update an existing pet
    +    api_instance.updatePet(body)
    +except ApiException as e:
    +    print("Exception when calling PetApi->updatePet: %s\n" % e)
    +

    Parameters

    @@ -2673,6 +2937,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -2844,6 +3110,50 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet that needs to be updated
    +my $name = name_example; # String | Updated name of the pet
    +my $status = status_example; # String | Updated status of the pet
    +
    +eval { 
    +    $api_instance->updatePetWithForm(petId => $petId, name => $name, status => $status);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->updatePetWithForm: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | ID of pet that needs to be updated
    +name = name_example # String | Updated name of the pet (optional)
    +status = status_example # String | Updated status of the pet (optional)
    +
    +try: 
    +    # Updates a pet in the store with form data
    +    api_instance.updatePetWithForm(petId, name=name, status=status)
    +except ApiException as e:
    +    print("Exception when calling PetApi->updatePetWithForm: %s\n" % e)
    +

    Parameters

    @@ -2999,6 +3309,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3177,6 +3489,52 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet to update
    +my $additionalMetadata = additionalMetadata_example; # String | Additional data to pass to server
    +my $file = /path/to/file.txt; # File | file to upload
    +
    +eval { 
    +    my $result = $api_instance->uploadFile(petId => $petId, additionalMetadata => $additionalMetadata, file => $file);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->uploadFile: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | ID of pet to update
    +additionalMetadata = additionalMetadata_example # String | Additional data to pass to server (optional)
    +file = /path/to/file.txt # File | file to upload (optional)
    +
    +try: 
    +    # uploads an image
    +    api_response = api_instance.uploadFile(petId, additionalMetadata=additionalMetadata, file=file)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->uploadFile: %s\n" % e)
    +

    Parameters

    @@ -3375,6 +3733,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3509,6 +3869,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $orderId = orderId_example; # String | ID of the order that needs to be deleted
    +
    +eval { 
    +    $api_instance->deleteOrder(orderId => $orderId);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->deleteOrder: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +orderId = orderId_example # String | ID of the order that needs to be deleted
    +
    +try: 
    +    # Delete purchase order by ID
    +    api_instance.deleteOrder(orderId)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->deleteOrder: %s\n" % e)
    +

    Parameters

    @@ -3531,7 +3925,7 @@ try { "description" : "ID of the order that needs to be deleted", "required" : true, "type" : "string", - "minimum" : 1 + "minimum" : 1.0 }; var schema = schemaWrapper; @@ -3593,6 +3987,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3757,6 +4153,50 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +# Configure API key authorization: api_key
    +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
    +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +
    +eval { 
    +    my $result = $api_instance->getInventory();
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->getInventory: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure API key authorization: api_key
    +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
    +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +
    +try: 
    +    # Returns pet inventories by status
    +    api_response = api_instance.getInventory()
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->getInventory: %s\n" % e)
    +

    Parameters

    @@ -3842,6 +4282,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3983,6 +4425,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $orderId = 789; # Long | ID of pet that needs to be fetched
    +
    +eval { 
    +    my $result = $api_instance->getOrderById(orderId => $orderId);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->getOrderById: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +orderId = 789 # Long | ID of pet that needs to be fetched
    +
    +try: 
    +    # Find purchase order by ID
    +    api_response = api_instance.getOrderById(orderId)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->getOrderById: %s\n" % e)
    +

    Parameters

    @@ -4005,8 +4483,8 @@ try { "description" : "ID of pet that needs to be fetched", "required" : true, "type" : "integer", - "maximum" : 5, - "minimum" : 1, + "maximum" : 5.0, + "minimum" : 1.0, "format" : "int64" }; var schema = schemaWrapper; @@ -4111,6 +4589,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4252,6 +4732,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet
    +
    +eval { 
    +    my $result = $api_instance->placeOrder(body => $body);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->placeOrder: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +body =  # Order | order placed for purchasing the pet
    +
    +try: 
    +    # Place an order for a pet
    +    api_response = api_instance.placeOrder(body)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->placeOrder: %s\n" % e)
    +

    Parameters

    @@ -4389,6 +4905,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4523,6 +5041,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object
    +
    +eval { 
    +    $api_instance->createUser(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # User | Created user object
    +
    +try: 
    +    # Create user
    +    api_instance.createUser(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUser: %s\n" % e)
    +

    Parameters

    @@ -4615,6 +5167,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4749,6 +5303,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = [WWW::SwaggerClient::Object::array[User]->new()]; # array[User] | List of user object
    +
    +eval { 
    +    $api_instance->createUsersWithArrayInput(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUsersWithArrayInput: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # array[User] | List of user object
    +
    +try: 
    +    # Creates list of users with given input array
    +    api_instance.createUsersWithArrayInput(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUsersWithArrayInput: %s\n" % e)
    +

    Parameters

    @@ -4844,6 +5432,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4978,6 +5568,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = [WWW::SwaggerClient::Object::array[User]->new()]; # array[User] | List of user object
    +
    +eval { 
    +    $api_instance->createUsersWithListInput(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUsersWithListInput: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # array[User] | List of user object
    +
    +try: 
    +    # Creates list of users with given input array
    +    api_instance.createUsersWithListInput(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUsersWithListInput: %s\n" % e)
    +

    Parameters

    @@ -5073,6 +5697,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5207,6 +5833,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The name that needs to be deleted
    +
    +eval { 
    +    $api_instance->deleteUser(username => $username);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->deleteUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The name that needs to be deleted
    +
    +try: 
    +    # Delete user
    +    api_instance.deleteUser(username)
    +except ApiException as e:
    +    print("Exception when calling UserApi->deleteUser: %s\n" % e)
    +

    Parameters

    @@ -5290,6 +5950,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5431,6 +6093,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The name that needs to be fetched. Use user1 for testing. 
    +
    +eval { 
    +    my $result = $api_instance->getUserByName(username => $username);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->getUserByName: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The name that needs to be fetched. Use user1 for testing. 
    +
    +try: 
    +    # Get user by user name
    +    api_response = api_instance.getUserByName(username)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling UserApi->getUserByName: %s\n" % e)
    +

    Parameters

    @@ -5556,6 +6254,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5705,6 +6405,44 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The user name for login
    +my $password = password_example; # String | The password for login in clear text
    +
    +eval { 
    +    my $result = $api_instance->loginUser(username => $username, password => $password);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->loginUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The user name for login
    +password = password_example # String | The password for login in clear text
    +
    +try: 
    +    # Logs user into the system
    +    api_response = api_instance.loginUser(username, password)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling UserApi->loginUser: %s\n" % e)
    +

    Parameters

    @@ -5873,6 +6611,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5999,6 +6739,38 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +
    +eval { 
    +    $api_instance->logoutUser();
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->logoutUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +
    +try: 
    +    # Logs out current logged in user session
    +    api_instance.logoutUser()
    +except ApiException as e:
    +    print("Exception when calling UserApi->logoutUser: %s\n" % e)
    +

    Parameters

    @@ -6040,6 +6812,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -6182,6 +6956,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | name that need to be deleted
    +my $body = WWW::SwaggerClient::Object::User->new(); # User | Updated user object
    +
    +eval { 
    +    $api_instance->updateUser(username => $username, body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->updateUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | name that need to be deleted
    +body =  # User | Updated user object
    +
    +try: 
    +    # Updated user
    +    api_instance.updateUser(username, body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->updateUser: %s\n" % e)
    +

    Parameters

    @@ -6303,7 +7113,7 @@ try {
    - Generated 2017-01-04T12:09:28.510+01:00 + Generated 2017-01-16T09:17:32.398-08:00
    From 545ee0c3380b899ec104b7f7f39007b32727f85a Mon Sep 17 00:00:00 2001 From: Bartek Kryza Date: Tue, 17 Jan 2017 03:36:12 +0100 Subject: [PATCH 254/269] Moved bash version detection to top and improved logic (#4578) --- .../src/main/resources/bash/client.mustache | 22 ++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/bash/client.mustache b/modules/swagger-codegen/src/main/resources/bash/client.mustache index 5a11334690d..934fddcbe8c 100644 --- a/modules/swagger-codegen/src/main/resources/bash/client.mustache +++ b/modules/swagger-codegen/src/main/resources/bash/client.mustache @@ -25,6 +25,20 @@ # {{#externalDocs}}{{url}}{{/externalDocs}} # +############################################################################### +# +# Make sure Bash is at least in version 4.3 +# +############################################################################### +if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ + && ! (("${BASH_VERSION:0:1}" >= "5")); then + echo "" + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + echo "" + exit 1 +fi ############################################################################### # @@ -899,14 +913,6 @@ call_{{operationId}}() { ############################################################################## -# Make sure Bash is at least in version 4.3 -if [[ ${BASH_VERSION:0:1} < 4 && ${BASH_VERSION:2:1} < 3 ]]; then - echo "Sorry - your Bash version is ${BASH_VERSION}" - echo "" - echo "You need at least Bash 4.3 to run this script." - exit 1 -fi - # Check dependencies type curl >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } From 55443daebca4de313b58156330e9b3fa1f242343 Mon Sep 17 00:00:00 2001 From: Damien Pontifex Date: Tue, 17 Jan 2017 10:52:33 +0800 Subject: [PATCH 255/269] Extends obj using Object.assign (#4562) --- .../resources/typescript-angular/api.mustache | 16 +--- .../typescript-angular2/api.mustache | 17 +--- .../resources/typescript-node/api.mustache | 10 +-- .../typescript-angular/API/Client/PetApi.ts | 65 ++++++-------- .../typescript-angular/API/Client/StoreApi.ts | 37 +++----- .../typescript-angular/API/Client/UserApi.ts | 65 ++++++-------- .../typescript-angular2/default/api/PetApi.ts | 41 +++------ .../default/api/StoreApi.ts | 23 +---- .../default/api/UserApi.ts | 31 ++----- .../typescript-angular2/npm/README.md | 4 +- .../typescript-angular2/npm/api/PetApi.ts | 41 +++------ .../typescript-angular2/npm/api/StoreApi.ts | 23 +---- .../typescript-angular2/npm/api/UserApi.ts | 31 ++----- .../typescript-angular2/npm/package.json | 2 +- .../petstore/typescript-node/default/api.ts | 86 +++++-------------- .../petstore/typescript-node/npm/api.ts | 86 +++++-------------- .../petstore/typescript-node/npm/client.ts | 2 +- 17 files changed, 161 insertions(+), 419 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 6a426c806f1..cf6665e7937 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -24,15 +24,6 @@ namespace {{package}} { } } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - {{#operation}} /** * {{summary}} @@ -44,7 +35,7 @@ namespace {{package}} { .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); {{#hasFormParams}} let formParams: any = {}; @@ -75,10 +66,9 @@ namespace {{package}} { formParams['{{baseName}}'] = {{paramName}}; {{/formParams}} - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: '{{httpMethod}}', url: localVarPath, - json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, {{#bodyParam}}data: {{paramName}}, {{/bodyParam}} {{#hasFormParams}}data: this.$httpParamSerializer(formParams), @@ -88,7 +78,7 @@ namespace {{package}} { }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache index d62224930ef..612354bb866 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.mustache @@ -35,21 +35,6 @@ export class {{classname}} { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - {{#operation}} /** * {{summary}} @@ -213,7 +198,7 @@ export class {{classname}} { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); 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 48bbaabf5b0..7fe4c99ad8e 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -183,14 +183,6 @@ export class {{classname}} { } {{/isOAuth}} {{/authMethods}} - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } {{#operation}} /** * {{summary}} @@ -201,7 +193,7 @@ export class {{classname}} { const localVarPath = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; {{#allParams}}{{#required}} diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index ec5ab968c9d..625b5adbce9 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -29,15 +29,6 @@ namespace API.Client { } } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - /** * Add a new pet to the store * @@ -47,18 +38,17 @@ namespace API.Client { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -74,23 +64,22 @@ namespace API.Client { .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } headerParams['api_key'] = apiKey; - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'DELETE', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -104,21 +93,20 @@ namespace API.Client { const localVarPath = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); if (status !== undefined) { queryParameters['status'] = status; } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -132,21 +120,20 @@ namespace API.Client { const localVarPath = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); if (tags !== undefined) { queryParameters['tags'] = tags; } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -161,21 +148,20 @@ namespace API.Client { .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'petId' is not null or undefined if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -189,18 +175,17 @@ namespace API.Client { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'PUT', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -217,7 +202,7 @@ namespace API.Client { .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; // verify required parameter 'petId' is not null or undefined @@ -230,17 +215,16 @@ namespace API.Client { formParams['status'] = status; - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: false, data: this.$httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -257,7 +241,7 @@ namespace API.Client { .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; // verify required parameter 'petId' is not null or undefined @@ -270,17 +254,16 @@ namespace API.Client { formParams['file'] = file; - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: false, data: this.$httpParamSerializer(formParams), params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } 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 9be77cc81a1..779eaad3338 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -29,15 +29,6 @@ namespace API.Client { } } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -48,21 +39,20 @@ namespace API.Client { .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'DELETE', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -75,17 +65,16 @@ namespace API.Client { const localVarPath = this.basePath + '/store/inventory'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -100,21 +89,20 @@ namespace API.Client { .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'orderId' is not null or undefined if (orderId === null || orderId === undefined) { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -128,18 +116,17 @@ namespace API.Client { const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index cd69c69c47e..083bb57f4a8 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -29,15 +29,6 @@ namespace API.Client { } } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - /** * Create user * This can only be done by the logged in user. @@ -47,18 +38,17 @@ namespace API.Client { const localVarPath = this.basePath + '/user'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -72,18 +62,17 @@ namespace API.Client { const localVarPath = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -97,18 +86,17 @@ namespace API.Client { const localVarPath = this.basePath + '/user/createWithList'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'POST', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -123,21 +111,20 @@ namespace API.Client { .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'DELETE', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -152,21 +139,20 @@ namespace API.Client { .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -181,7 +167,7 @@ namespace API.Client { const localVarPath = this.basePath + '/user/login'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); if (username !== undefined) { queryParameters['username'] = username; } @@ -190,16 +176,15 @@ namespace API.Client { queryParameters['password'] = password; } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -212,17 +197,16 @@ namespace API.Client { const localVarPath = this.basePath + '/user/logout'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { method: 'GET', url: localVarPath, - json: true, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); @@ -238,22 +222,21 @@ namespace API.Client { .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); // verify required parameter 'username' is not null or undefined if (username === null || username === undefined) { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - let httpRequestParams: any = { + let httpRequestParams: ng.IRequestConfig = { method: 'PUT', url: localVarPath, - json: true, data: body, params: queryParameters, headers: headerParams }; if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } return this.$http(httpRequestParams); diff --git a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts index 535d21d66d0..6989fd1629f 100644 --- a/samples/client/petstore/typescript-angular2/default/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/PetApi.ts @@ -40,21 +40,6 @@ export class PetApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Add a new pet to the store * @@ -231,7 +216,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -281,7 +266,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -330,7 +315,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -379,7 +364,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -409,11 +394,6 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) { - headers.set('api_key', this.configuration.apiKey); - } - // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { @@ -423,6 +403,11 @@ export class PetApi { headers.set('Authorization', 'Bearer ' + accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) { + headers.set('api_key', this.configuration.apiKey); + } + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -431,7 +416,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -479,7 +464,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -542,7 +527,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -605,7 +590,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts index 344d1f1b257..e44e80b70f8 100644 --- a/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/StoreApi.ts @@ -40,21 +40,6 @@ export class StoreApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -151,7 +136,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -189,7 +174,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -227,7 +212,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -264,7 +249,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts index bb7884ea636..bb921d51a95 100644 --- a/samples/client/petstore/typescript-angular2/default/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/default/api/UserApi.ts @@ -40,21 +40,6 @@ export class UserApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Create user * This can only be done by the logged in user. @@ -216,7 +201,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -253,7 +238,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -290,7 +275,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -328,7 +313,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -366,7 +351,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -409,7 +394,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -442,7 +427,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -484,7 +469,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index b1cac56e5e8..a445859300a 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701111439 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701160843 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701111439 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701160843 --save ``` _unPublished (not recommended):_ diff --git a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts index 535d21d66d0..6989fd1629f 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/PetApi.ts @@ -40,21 +40,6 @@ export class PetApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Add a new pet to the store * @@ -231,7 +216,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -281,7 +266,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -330,7 +315,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -379,7 +364,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -409,11 +394,6 @@ export class PetApi { 'application/xml' ]; - // authentication (api_key) required - if (this.configuration.apiKey) { - headers.set('api_key', this.configuration.apiKey); - } - // authentication (petstore_auth) required // oauth required if (this.configuration.accessToken) { @@ -423,6 +403,11 @@ export class PetApi { headers.set('Authorization', 'Bearer ' + accessToken); } + // authentication (api_key) required + if (this.configuration.apiKey) { + headers.set('api_key', this.configuration.apiKey); + } + let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, @@ -431,7 +416,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -479,7 +464,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -542,7 +527,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -605,7 +590,7 @@ export class PetApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts index 344d1f1b257..e44e80b70f8 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/StoreApi.ts @@ -40,21 +40,6 @@ export class StoreApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -151,7 +136,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -189,7 +174,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -227,7 +212,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -264,7 +249,7 @@ export class StoreApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts index bb7884ea636..bb921d51a95 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/UserApi.ts @@ -40,21 +40,6 @@ export class UserApi { } } - /** - * - * Extends object by coping non-existing properties. - * @param objA object to be extended - * @param objB source object - */ - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - (objA as any)[key] = (objB as any)[key]; - } - } - return objA; - } - /** * Create user * This can only be done by the logged in user. @@ -216,7 +201,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -253,7 +238,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -290,7 +275,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -328,7 +313,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -366,7 +351,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -409,7 +394,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -442,7 +427,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -484,7 +469,7 @@ export class UserApi { // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index e6d3d71d494..2c5ecc8de11 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201701111439", + "version": "0.0.1-SNAPSHOT.201701160843", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 9deaabf6d00..edfe1a4fef3 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -174,14 +174,6 @@ export class PetApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Add a new pet to the store * @@ -190,7 +182,7 @@ export class PetApi { public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -202,7 +194,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -242,7 +233,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -261,7 +252,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -298,7 +288,7 @@ export class PetApi { public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -314,7 +304,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -351,7 +340,7 @@ export class PetApi { public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -367,7 +356,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -405,7 +393,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -422,7 +410,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -461,7 +448,7 @@ export class PetApi { public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -473,7 +460,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -514,7 +500,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -539,7 +525,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -575,11 +560,11 @@ export class PetApi { * @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; }> { + public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -605,7 +590,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -674,14 +658,6 @@ export class StoreApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -691,7 +667,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -708,7 +684,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -742,7 +717,7 @@ export class StoreApi { public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -754,7 +729,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -792,7 +766,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -809,7 +783,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -844,7 +817,7 @@ export class StoreApi { public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -856,7 +829,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -924,14 +896,6 @@ export class UserApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Create user * This can only be done by the logged in user. @@ -940,7 +904,7 @@ export class UserApi { public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -952,7 +916,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -988,7 +951,7 @@ export class UserApi { public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1000,7 +963,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -1036,7 +998,7 @@ export class UserApi { public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1048,7 +1010,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -1085,7 +1046,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1102,7 +1063,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1138,7 +1098,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1155,7 +1115,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1191,7 +1150,7 @@ export class UserApi { public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1211,7 +1170,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1245,7 +1203,7 @@ export class UserApi { public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1257,7 +1215,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1294,7 +1251,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1311,7 +1268,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index 9deaabf6d00..edfe1a4fef3 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -174,14 +174,6 @@ export class PetApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Add a new pet to the store * @@ -190,7 +182,7 @@ export class PetApi { public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -202,7 +194,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -242,7 +233,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -261,7 +252,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -298,7 +288,7 @@ export class PetApi { public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -314,7 +304,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -351,7 +340,7 @@ export class PetApi { public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -367,7 +356,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -405,7 +393,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -422,7 +410,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -461,7 +448,7 @@ export class PetApi { public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -473,7 +460,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -514,7 +500,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -539,7 +525,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -575,11 +560,11 @@ export class PetApi { * @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; }> { + public uploadFile (petId: number, additionalMetadata?: string, file?: Buffer) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -605,7 +590,6 @@ export class PetApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -674,14 +658,6 @@ export class StoreApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -691,7 +667,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -708,7 +684,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -742,7 +717,7 @@ export class StoreApi { public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -754,7 +729,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -792,7 +766,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -809,7 +783,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -844,7 +817,7 @@ export class StoreApi { public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -856,7 +829,6 @@ export class StoreApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -924,14 +896,6 @@ export class UserApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Create user * This can only be done by the logged in user. @@ -940,7 +904,7 @@ export class UserApi { public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -952,7 +916,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -988,7 +951,7 @@ export class UserApi { public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1000,7 +963,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -1036,7 +998,7 @@ export class UserApi { public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1048,7 +1010,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; @@ -1085,7 +1046,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1102,7 +1063,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1138,7 +1098,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1155,7 +1115,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1191,7 +1150,7 @@ export class UserApi { public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1211,7 +1170,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1245,7 +1203,7 @@ export class UserApi { public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1257,7 +1215,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, }; @@ -1294,7 +1251,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1311,7 +1268,6 @@ export class UserApi { headers: headerParams, uri: localVarPath, useQuerystring: this._useQuerystring, - json: true, body: body, }; diff --git a/samples/client/petstore/typescript-node/npm/client.ts b/samples/client/petstore/typescript-node/npm/client.ts index 79b8737c92b..c35c1cf1e5b 100644 --- a/samples/client/petstore/typescript-node/npm/client.ts +++ b/samples/client/petstore/typescript-node/npm/client.ts @@ -34,7 +34,7 @@ petApi.addPet(pet) }) .then((res) => { console.log('Updated pet using POST form'); - return petApi.uploadFile(petId, undefined, fs.createReadStream('sample.png')); + return petApi.uploadFile(petId, undefined, fs.readFileSync('sample.png')); }) .then((res) => { console.log('Uploaded image'); From 4c7d1338dc05abca93ca8b075e33b5ce5bbf99fe Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Mon, 16 Jan 2017 21:59:31 -0600 Subject: [PATCH 256/269] [csharp] Client nuspec (#4576) * [csharp] Client nuspec * [csharp] remove carriage returns from nuspec --- .../languages/CSharpClientCodegen.java | 1 + .../src/main/resources/csharp/README.mustache | 14 ++++++ .../src/main/resources/csharp/nuspec.mustache | 45 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 526fffeda18..cccc2f23bfe 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -312,6 +312,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj")); + supportingFiles.add(new SupportingFile("nuspec.mustache", packageFolder, packageName + ".nuspec")); if(Boolean.FALSE.equals(excludeTests)) { // NOTE: This exists here rather than previous excludeTests block because the test project is considered an optional project file. diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index bb228814338..8c08c0e8667 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -51,6 +51,20 @@ using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; ``` + + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out {{packageName}}.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + ## Getting Started diff --git a/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache b/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache new file mode 100644 index 00000000000..eaf4b0e3381 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache @@ -0,0 +1,45 @@ + + + + + $id$ + {{packageTitle}} + + + $version$ + + + $author$ + + + $author$ + false + false + + + {{packageDescription}}{{#termsOfService}} + {{termsOfService}}{{/termsOfService}}{{#licenseUrl}} + {{licenseUrl}}{{/licenseUrl}} + + + + + + {{#generatePropertyChanged}} + + {{/generatePropertyChanged}} + + + + + + + + {{#generatePropertyChanged}} + + {{/generatePropertyChanged}} + + + \ No newline at end of file From a846a571b3d44f3400b3e9862730339470b3b1cb Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 17 Jan 2017 14:44:40 +0800 Subject: [PATCH 257/269] add tips about windows class path --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 544c7c226f4..f1ebbb432ad 100644 --- a/README.md +++ b/README.md @@ -335,6 +335,10 @@ You would then compile your library in the `output/myLibrary` folder with `mvn p ``` java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen ``` +For Windows users, you will need to use `;` instead of `:` in the classpath, e.g. +``` +java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar;modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen +``` Note the `myClientCodegen` is an option now, and you can use the usual arguments for generating your library: From 0a559f0dd2ad3a60ad20c005aab6d9dfcd846235 Mon Sep 17 00:00:00 2001 From: Dan Mikita Date: Tue, 17 Jan 2017 02:26:30 -0500 Subject: [PATCH 258/269] Add support for modifier within the Jaxb XMLElement annotation (#4433) * fixes #4432 Adding support for the modifier within the Jaxb XMLElement annotation. Updated README with JaxbAnnotations configuration option. * #4432 Running the Petstore files --- .../swagger-codegen-maven-plugin/README.md | 3 +- .../resources/JavaJaxRS/cxf/pojo.mustache | 4 +- .../java/okhttp-gson/pom.xml | 11 +- .../java/io/swagger/client/api/FakeApi.java | 299 +++++++++--------- .../src/gen/java/io/swagger/api/PetApi.java | 150 ++++----- .../src/gen/java/io/swagger/api/StoreApi.java | 92 +++--- .../src/gen/java/io/swagger/api/UserApi.java | 140 ++++---- 7 files changed, 360 insertions(+), 339 deletions(-) diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index a7284fdb3c5..cc54e2ad447 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -45,7 +45,8 @@ mvn clean compile - `modelPackage` - the package to use for generated model objects/classes - `apiPackage` - the package to use for generated api objects/classes - `invokerPackage` - the package to use for the generated invoker objects -- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums. +- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums +- `useJaxbAnnotations` - enable Jaxb annotations inside the generated models - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index 2d74634919c..acce6134304 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -25,8 +25,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{>enumClass}}{{/items}}{{/items.isEnum}} {{#useJaxbAnnotations}} - @XmlElement(name="{{baseName}}") -{{/useJaxbAnnotations}} + @XmlElement(name="{{baseName}}"{{#required}}, required = {{required}}{{/required}}) +{{/useJaxbAnnotations}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} diff --git a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml index d6ce1873282..be07768b92e 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml +++ b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html *_/ ' \" =end -- \\r\\n \\n \\r + repo + + + @@ -129,7 +137,6 @@ joda-time ${jodatime-version} - junit @@ -150,4 +157,4 @@ 4.12 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 0d0407f94b3..8a4e08dc244 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,146 +9,159 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testCodeInjectEndRnNR */ - private com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (testCodeInjectEndRnNR != null) - localVarFormParams.put("test code inject */ ' " =end -- \r\n \n \r", testCodeInjectEndRnNR); - - final String[] localVarAccepts = { - "application/json", "*_/ ' =end -- " - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "*_/ ' =end -- " - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testCodeInjectEndRnNR(String testCodeInjectEndRnNR) throws ApiException { - testCodeInjectEndRnNRWithHttpInfo(testCodeInjectEndRnNR); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testCodeInjectEndRnNRWithHttpInfo(String testCodeInjectEndRnNR) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, null, null); - return apiClient.execute(call); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(String testCodeInjectEndRnNR, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testCodeInjectEndRnNR */ + private com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (testCodeInjectEndRnNR != null) + localVarFormParams.put("test code inject */ ' " =end -- \r\n \n \r", testCodeInjectEndRnNR); + + final String[] localVarAccepts = { + "application/json", "*_/ ' =end -- " + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "*_/ ' =end -- " + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testCodeInjectEndRnNRValidateBeforeCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testCodeInjectEndRnNR(String testCodeInjectEndRnNR) throws ApiException { + testCodeInjectEndRnNRWithHttpInfo(testCodeInjectEndRnNR); + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testCodeInjectEndRnNRWithHttpInfo(String testCodeInjectEndRnNR) throws ApiException { + com.squareup.okhttp.Call call = testCodeInjectEndRnNRValidateBeforeCall(testCodeInjectEndRnNR, null, null); + return apiClient.execute(call); + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(String testCodeInjectEndRnNR, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testCodeInjectEndRnNRValidateBeforeCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java index 4ef2db0e204..edd25fbd563 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -1,75 +1,75 @@ -package io.swagger.api; - -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -@Path("/") -@Api(value = "/", description = "") -public interface PetApi { - - @POST - @Path("/pet") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) - public void addPet(Pet body); - - @DELETE - @Path("/pet/{petId}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Deletes a pet", tags={ "pet", }) - public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); - - @GET - @Path("/pet/findByStatus") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) - public List findPetsByStatus(@QueryParam("status")List status); - - @GET - @Path("/pet/findByTags") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) - public List findPetsByTags(@QueryParam("tags")List tags); - - @GET - @Path("/pet/{petId}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find pet by ID", tags={ "pet", }) - public Pet getPetById(@PathParam("petId") Long petId); - - @PUT - @Path("/pet") - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Update an existing pet", tags={ "pet", }) - public void updatePet(Pet body); - - @POST - @Path("/pet/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) - public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); - - @POST - @Path("/pet/{petId}/uploadImage") - @Consumes({ "multipart/form-data" }) - @Produces({ "application/json" }) - @ApiOperation(value = "uploads an image", tags={ "pet" }) - public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); -} - +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface PetApi { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + public void addPet(Pet body); + + @DELETE + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + public List findPetsByStatus(@QueryParam("status")List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + public List findPetsByTags(@QueryParam("tags")List tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + public Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + public void updatePet(Pet body); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ "pet" }) + public ModelApiResponse uploadFile(@PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file" , required = false) Attachment fileDetail); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java index e26c47769b4..50f1b618273 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -1,46 +1,46 @@ -package io.swagger.api; - -import java.util.Map; -import io.swagger.model.Order; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -@Path("/") -@Api(value = "/", description = "") -public interface StoreApi { - - @DELETE - @Path("/store/order/{orderId}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) - public void deleteOrder(@PathParam("orderId") String orderId); - - @GET - @Path("/store/inventory") - @Produces({ "application/json" }) - @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) - public Map getInventory(); - - @GET - @Path("/store/order/{orderId}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) - public Order getOrderById(@PathParam("orderId") Long orderId); - - @POST - @Path("/store/order") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Place an order for a pet", tags={ "store" }) - public Order placeOrder(Order body); -} - +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface StoreApi { + + @DELETE + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + public void deleteOrder(@PathParam("orderId") String orderId); + + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + public Map getInventory(); + + @GET + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + public Order getOrderById(@PathParam("orderId") Long orderId); + + @POST + @Path("/store/order") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + public Order placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java index a51b1fe0c70..20347b8650c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -1,70 +1,70 @@ -package io.swagger.api; - -import java.util.List; -import io.swagger.model.User; - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; - -@Path("/") -@Api(value = "/", description = "") -public interface UserApi { - - @POST - @Path("/user") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Create user", tags={ "user", }) - public void createUser(User body); - - @POST - @Path("/user/createWithArray") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithArrayInput(List body); - - @POST - @Path("/user/createWithList") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) - public void createUsersWithListInput(List body); - - @DELETE - @Path("/user/{username}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Delete user", tags={ "user", }) - public void deleteUser(@PathParam("username") String username); - - @GET - @Path("/user/{username}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Get user by user name", tags={ "user", }) - public User getUserByName(@PathParam("username") String username); - - @GET - @Path("/user/login") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs user into the system", tags={ "user", }) - public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); - - @GET - @Path("/user/logout") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) - public void logoutUser(); - - @PUT - @Path("/user/{username}") - @Produces({ "application/xml", "application/json" }) - @ApiOperation(value = "Updated user", tags={ "user" }) - public void updateUser(@PathParam("username") String username, User body); -} - +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface UserApi { + + @POST + @Path("/user") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", tags={ "user", }) + public void createUser(User body); + + @POST + @Path("/user/createWithArray") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithArrayInput(List body); + + @POST + @Path("/user/createWithList") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithListInput(List body); + + @DELETE + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", tags={ "user", }) + public void deleteUser(@PathParam("username") String username); + + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ "user", }) + public User getUserByName(@PathParam("username") String username); + + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ "user", }) + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + + @GET + @Path("/user/logout") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + public void logoutUser(); + + @PUT + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", tags={ "user" }) + public void updateUser(@PathParam("username") String username, User body); +} + From da01b2e71abcbff241b3fafea06d6abb0e03516b Mon Sep 17 00:00:00 2001 From: Sreenidhi Sreesha Date: Tue, 17 Jan 2017 23:27:56 -0800 Subject: [PATCH 259/269] Add title field to CodegenProperty (#4590) Earlier CodegenProperty did not have title field. 'title' information of the property was lost while converting from Property to CodegenProperty. This change fixes it. --- .../main/java/io/swagger/codegen/CodegenProperty.java | 9 +++++++-- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 5318d779e5b..3caf46d78f6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -7,8 +7,9 @@ import java.util.Map; import java.util.Objects; public class CodegenProperty implements Cloneable { - public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, - dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, containerType; + public String baseName, complexType, getter, setter, description, datatype, + datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam, + baseType, containerType, title; public String unescapedDescription; @@ -77,6 +78,7 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((example == null) ? 0 : example.hashCode()); result = prime * result + (exclusiveMaximum ? 13:31); result = prime * result + (exclusiveMinimum ? 13:31); @@ -149,6 +151,9 @@ public class CodegenProperty implements Cloneable { if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) { return false; } + if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) { + return false; + } if ((this.datatype == null) ? (other.datatype != null) : !this.datatype.equals(other.datatype)) { return false; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 09a1329a9da..bc973ca97e3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1463,6 +1463,7 @@ public class DefaultCodegen { property.nameInCamelCase = camelize(property.name, false); property.description = escapeText(p.getDescription()); property.unescapedDescription = p.getDescription(); + property.title = p.getTitle(); property.getter = "get" + getterAndSetterCapitalize(name); property.setter = "set" + getterAndSetterCapitalize(name); property.example = toExampleValue(p); From da6b57f3fc05e0428ec0bf50c6fd3cb4cc58e716 Mon Sep 17 00:00:00 2001 From: Jim Schubert Date: Wed, 18 Jan 2017 03:43:12 -0500 Subject: [PATCH 260/269] [aspnetcore] use default in model constructors, supports enums (#4573) * [aspnetcore] Use default rather than null in ctor See original issue #3608 This adds same model constructor logic to aspnetcore as what was added to csharp generator by PR #4145. This doesn't include NancyFX because model construction relies more on object initialization in that generator. * [aspnetcore] ctor defaults + enum support This follows up to #4145, and modifies model constructors to use default(x) instead of initializing to nulls. default(x) works in all cases using intuitive default values it is intended to support. Example: csharp> public enum Color { RED = -1, BLUE = 0, GREEN } csharp> var color = default(Color) csharp> color BLUE In the above example, The default of BLUE=0 is expected. For nullable enums, this would be null as a default. The aspnetcore generated code is also updated to support enums and nested enums to account for changed to the petstore.yaml used to generate the sample. * [aspnetcore] Regenerate sample --- .../resources/aspnetcore/enumClass.mustache | 14 ++++++ .../src/main/resources/aspnetcore/global.json | 2 +- .../main/resources/aspnetcore/model.mustache | 34 ++++++++++++-- .../aspnetcore/project.json.mustache | 3 +- .../server/petstore/aspnetcore/IO.Swagger.sln | 10 ++-- .../server/petstore/aspnetcore/global.json | 4 +- .../src/IO.Swagger/IO.Swagger.xproj | 2 +- .../src/IO.Swagger/Models/ApiResponse.cs | 7 ++- .../src/IO.Swagger/Models/Category.cs | 6 +-- .../aspnetcore/src/IO.Swagger/Models/Order.cs | 47 ++++++++++++++----- .../aspnetcore/src/IO.Swagger/Models/Pet.cs | 47 ++++++++++++++----- .../aspnetcore/src/IO.Swagger/Models/Tag.cs | 6 +-- .../aspnetcore/src/IO.Swagger/Models/User.cs | 12 ++--- .../aspnetcore/src/IO.Swagger/project.json | 3 +- 14 files changed, 136 insertions(+), 61 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache new file mode 100644 index 00000000000..1a5850e28a9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache @@ -0,0 +1,14 @@ + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + { + {{#allowableValues}}{{#enumVars}} + /// + /// Enum {{name}} for {{{value}}} + /// + [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] + {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{/-last}}{{/enumVars}}{{/allowableValues}} + } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/global.json b/modules/swagger-codegen/src/main/resources/aspnetcore/global.json index e5360d025ec..175b2d57e38 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/global.json +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/global.json @@ -1,5 +1,5 @@ { - "projects": [ "src", "test" ], + "projects": [ "src" ], "sdk": { "version": "1.0.0-preview2-003121", "runtime": "coreclr" diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache index 58325e8fe24..101f85ce13f 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache @@ -13,18 +13,40 @@ using Newtonsoft.Json; {{#model}} namespace {{packageName}}.Models { +{{#isEnum}}{{>enumClass}}{{/isEnum}}{{^isEnum}} /// /// {{description}} /// [DataContract] public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}> { + {{#vars}} + {{#isEnum}} + {{>enumClass}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} + {{>enumClass}} + {{/items}} + {{/items.isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + [DataMember(Name="{{baseName}}")] + public {{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} { get; set; } + {{/isEnum}} + {{/vars}} + /// /// Initializes a new instance of the class. /// {{#vars}} /// {{#description}}{{description}}{{/description}}{{^description}}{{name}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. {{/vars}} - public {{classname}}({{#vars}}{{{datatype}}} {{name}} = null{{#hasMore}}, {{/hasMore}}{{/vars}}) + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}) { {{#vars}}{{#required}}// to ensure "{{name}}" is required (not null) if ({{name}} == null) @@ -49,13 +71,14 @@ namespace {{packageName}}.Models } {{#vars}} + {{^isEnum}} /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} - /// {{{description}}}{{/description}} + /// {{description}}{{/description}} [DataMember(Name="{{baseName}}")] - public {{{datatype}}} {{name}} { get; set; } - + public {{{datatype}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + {{/isEnum}} {{/vars}} /// @@ -153,6 +176,7 @@ namespace {{packageName}}.Models #endregion Operators } +{{/isEnum}} {{/model}} {{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache index 432ba86d5a9..46a9071fde4 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache @@ -22,7 +22,8 @@ "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore": "1.0.0", "Swashbuckle.SwaggerGen": "6.0.0-beta901", - "Swashbuckle.SwaggerUi": "6.0.0-beta901" + "Swashbuckle.SwaggerUi": "6.0.0-beta901", + "Newtonsoft.Json": "9.0.1" }, "tools": { diff --git a/samples/server/petstore/aspnetcore/IO.Swagger.sln b/samples/server/petstore/aspnetcore/IO.Swagger.sln index 4289d2b3652..866d0d2802c 100644 --- a/samples/server/petstore/aspnetcore/IO.Swagger.sln +++ b/samples/server/petstore/aspnetcore/IO.Swagger.sln @@ -7,7 +7,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution global.json = global.json EndProjectSection EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{85CF9021-4522-4D1B-871B-D4C1C6483FA1}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,10 +15,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Release|Any CPU.Build.0 = Release|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/samples/server/petstore/aspnetcore/global.json b/samples/server/petstore/aspnetcore/global.json index e5360d025ec..ac4c4297ab6 100644 --- a/samples/server/petstore/aspnetcore/global.json +++ b/samples/server/petstore/aspnetcore/global.json @@ -1,7 +1,7 @@ { - "projects": [ "src", "test" ], + "projects": [ "src" ], "sdk": { - "version": "1.0.0-preview2-003121", + "version": "1.0.0-preview3-003171", "runtime": "coreclr" } } \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj b/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj index 2454fd383ae..577ab91b009 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj @@ -6,7 +6,7 @@ - {85CF9021-4522-4D1B-871B-D4C1C6483FA1} + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E} IO.Swagger .\obj .\bin\ diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs index 962d0de469e..2782644943b 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs @@ -20,19 +20,21 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// Describes the result of uploading an image resource /// [DataContract] public partial class ApiResponse : IEquatable { + /// /// Initializes a new instance of the class. /// /// Code. /// Type. /// Message. - public ApiResponse(int? Code = null, string Type = null, string Message = null) + public ApiResponse(int? Code = default(int?), string Type = default(string), string Message = default(string)) { this.Code = Code; this.Type = Type; @@ -45,20 +47,17 @@ namespace IO.Swagger.Models /// [DataMember(Name="code")] public int? Code { get; set; } - /// /// Gets or Sets Type /// [DataMember(Name="type")] public string Type { get; set; } - /// /// Gets or Sets Message /// [DataMember(Name="message")] public string Message { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs index 7bb9e6119ba..55a7bcdc113 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs @@ -20,18 +20,20 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A category for a pet /// [DataContract] public partial class Category : IEquatable { + /// /// Initializes a new instance of the class. /// /// Id. /// Name. - public Category(long? Id = null, string Name = null) + public Category(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; @@ -43,14 +45,12 @@ namespace IO.Swagger.Models ///
    [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs index b30b60be618..7b3d9cf31c7 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs @@ -20,12 +20,45 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// An order for a pets from the pet store /// [DataContract] public partial class Order : IEquatable { + /// + /// Order Status + /// + /// Order Status + public enum StatusEnum + { + + /// + /// Enum PlacedEnum for "placed" + /// + [EnumMember(Value = "placed")] + PlacedEnum, + + /// + /// Enum ApprovedEnum for "approved" + /// + [EnumMember(Value = "approved")] + ApprovedEnum, + + /// + /// Enum DeliveredEnum for "delivered" + /// + [EnumMember(Value = "delivered")] + DeliveredEnum + } + /// + /// Order Status + /// + /// Order Status + [DataMember(Name="status")] + public StatusEnum? Status { get; set; } + /// /// Initializes a new instance of the class. /// @@ -35,7 +68,7 @@ namespace IO.Swagger.Models /// ShipDate. /// Order Status. /// Complete (default to false). - public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, string Status = null, bool? Complete = null) + public Order(long? Id = default(long?), long? PetId = default(long?), int? Quantity = default(int?), DateTime? ShipDate = default(DateTime?), StatusEnum? Status = default(StatusEnum?), bool? Complete = false) { this.Id = Id; this.PetId = PetId; @@ -59,39 +92,27 @@ namespace IO.Swagger.Models ///
    [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets PetId /// [DataMember(Name="petId")] public long? PetId { get; set; } - /// /// Gets or Sets Quantity /// [DataMember(Name="quantity")] public int? Quantity { get; set; } - /// /// Gets or Sets ShipDate /// [DataMember(Name="shipDate")] public DateTime? ShipDate { get; set; } - - /// - /// Order Status - /// - /// Order Status - [DataMember(Name="status")] - public string Status { get; set; } - /// /// Gets or Sets Complete /// [DataMember(Name="complete")] public bool? Complete { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs index be90b4bbb1d..a6454c61726 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs @@ -20,12 +20,45 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A pet for sale in the pet store /// [DataContract] public partial class Pet : IEquatable { + /// + /// pet status in the store + /// + /// pet status in the store + public enum StatusEnum + { + + /// + /// Enum AvailableEnum for "available" + /// + [EnumMember(Value = "available")] + AvailableEnum, + + /// + /// Enum PendingEnum for "pending" + /// + [EnumMember(Value = "pending")] + PendingEnum, + + /// + /// Enum SoldEnum for "sold" + /// + [EnumMember(Value = "sold")] + SoldEnum + } + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name="status")] + public StatusEnum? Status { get; set; } + /// /// Initializes a new instance of the class. /// @@ -35,7 +68,7 @@ namespace IO.Swagger.Models /// PhotoUrls (required). /// Tags. /// pet status in the store. - public Pet(long? Id = null, Category Category = null, string Name = null, List PhotoUrls = null, List Tags = null, string Status = null) + public Pet(long? Id = default(long?), Category Category = default(Category), string Name = default(string), List PhotoUrls = default(List), List Tags = default(List), StatusEnum? Status = default(StatusEnum?)) { // to ensure "Name" is required (not null) if (Name == null) @@ -67,39 +100,27 @@ namespace IO.Swagger.Models ///
    [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Category /// [DataMember(Name="category")] public Category Category { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Gets or Sets PhotoUrls /// [DataMember(Name="photoUrls")] public List PhotoUrls { get; set; } - /// /// Gets or Sets Tags /// [DataMember(Name="tags")] public List Tags { get; set; } - /// - /// pet status in the store - /// - /// pet status in the store - [DataMember(Name="status")] - public string Status { get; set; } - - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs index 1a813910f15..ea2ca1d6c1e 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs @@ -20,18 +20,20 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A tag for a pet /// [DataContract] public partial class Tag : IEquatable { + /// /// Initializes a new instance of the class. /// /// Id. /// Name. - public Tag(long? Id = null, string Name = null) + public Tag(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; @@ -43,14 +45,12 @@ namespace IO.Swagger.Models ///
    [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs index c935fc09316..54b0a00d989 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs @@ -20,12 +20,14 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A User who is purchasing from the pet store /// [DataContract] public partial class User : IEquatable { + /// /// Initializes a new instance of the class. /// @@ -37,7 +39,7 @@ namespace IO.Swagger.Models /// Password. /// Phone. /// User Status. - public User(long? Id = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) + public User(long? Id = default(long?), string Username = default(string), string FirstName = default(string), string LastName = default(string), string Email = default(string), string Password = default(string), string Phone = default(string), int? UserStatus = default(int?)) { this.Id = Id; this.Username = Username; @@ -55,43 +57,36 @@ namespace IO.Swagger.Models ///
    [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Username /// [DataMember(Name="username")] public string Username { get; set; } - /// /// Gets or Sets FirstName /// [DataMember(Name="firstName")] public string FirstName { get; set; } - /// /// Gets or Sets LastName /// [DataMember(Name="lastName")] public string LastName { get; set; } - /// /// Gets or Sets Email /// [DataMember(Name="email")] public string Email { get; set; } - /// /// Gets or Sets Password /// [DataMember(Name="password")] public string Password { get; set; } - /// /// Gets or Sets Phone /// [DataMember(Name="phone")] public string Phone { get; set; } - /// /// User Status /// @@ -99,7 +94,6 @@ namespace IO.Swagger.Models [DataMember(Name="userStatus")] public int? UserStatus { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json b/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json index ca8ac967209..de2fe74640d 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json @@ -22,7 +22,8 @@ "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore": "1.0.0", "Swashbuckle.SwaggerGen": "6.0.0-beta901", - "Swashbuckle.SwaggerUi": "6.0.0-beta901" + "Swashbuckle.SwaggerUi": "6.0.0-beta901", + "Newtonsoft.Json": "9.0.1" }, "tools": { From 5db75d885e20f6fad2b0be2dc85e9060da343a23 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 18 Jan 2017 18:01:03 +0800 Subject: [PATCH 261/269] add Webever GmbH --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f1ebbb432ad..9484ad15135 100644 --- a/README.md +++ b/README.md @@ -842,6 +842,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [VMware](https://vmware.com/) - [W.UP](http://wup.hu/?siteLang=en) - [Wealthfront](https://www.wealthfront.com/) +- [Webever GmbH](http://webever.de/) - [WEXO A/S](https://www.wexo.dk/) - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) From c7ecb3c445e19e0a4a9fd95d9d5536a2da1b6b89 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 18 Jan 2017 18:16:41 +0800 Subject: [PATCH 262/269] update https://www.webever.de --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9484ad15135..77cbd9cf13e 100644 --- a/README.md +++ b/README.md @@ -842,7 +842,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [VMware](https://vmware.com/) - [W.UP](http://wup.hu/?siteLang=en) - [Wealthfront](https://www.wealthfront.com/) -- [Webever GmbH](http://webever.de/) +- [Webever GmbH](https://www.webever.de/) - [WEXO A/S](https://www.wexo.dk/) - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) From ee7f9fc56c6557c2cd03874790c50e0a0beedc62 Mon Sep 17 00:00:00 2001 From: jfiala Date: Thu, 19 Jan 2017 08:13:11 +0100 Subject: [PATCH 263/269] [Jaxrs] Add beanvalidation annotations and fix outer Enums (#4492) * add beanvalidation to jaxrs and add support for outer Enums #4091 * cleanup Codegen #4091 * cleanup samples #4091 * cleanup tabs * updated samples to petstore.yaml (before petstore.json) * add support for DecimalMin/DecimalMax/Min/Max #4091 * add check for hideGenerationTimestamp #4091 * replace tabs * correct line endings to lf --- .../io/swagger/codegen/DefaultCodegen.java | 42 +- .../languages/JavaJAXRSSpecServerCodegen.java | 72 +- .../resources/JavaJaxRS/spec/api.mustache | 3 + .../JavaJaxRS/spec/beanValidation.mustache | 53 + .../spec/beanValidationPathParams.mustache | 1 + .../spec/beanValidationQueryParams.mustache | 1 + .../JavaJaxRS/spec/enumClass.mustache | 37 +- .../JavaJaxRS/spec/enumOuterClass.mustache | 43 + .../JavaJaxRS/spec/formParams.mustache | 4 +- .../spec/generatedAnnotation.mustache | 4 +- .../resources/JavaJaxRS/spec/model.mustache | 7 +- .../JavaJaxRS/spec/pathParams.mustache | 2 +- .../resources/JavaJaxRS/spec/pojo.mustache | 2 +- .../resources/JavaJaxRS/spec/pom.mustache | 9 + .../JavaJaxRS/spec/queryParams.mustache | 2 +- .../jaxrs-spec/.swagger-codegen-ignore | 23 + samples/server/petstore/jaxrs-spec/pom.xml | 13 +- .../java/io/swagger/api/PetApi.java} | 296 ++-- .../java/io/swagger/api}/RestApplication.java | 2 +- .../java/io/swagger/api/StoreApi.java} | 131 +- .../java/io/swagger/api/UserApi.java} | 231 +-- .../java/io/swagger}/model/Category.java | 178 +- .../io/swagger/model/ModelApiResponse.java | 110 ++ .../java/io/swagger}/model/Order.java | 363 ++-- .../java/io/swagger}/model/Pet.java | 373 ++-- .../java/io/swagger}/model/Tag.java | 178 +- .../java/io/swagger}/model/User.java | 408 ++--- .../server/petstore/jaxrs-spec/swagger.json | 1503 +++++++++-------- 28 files changed, 2335 insertions(+), 1756 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache create mode 100644 samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample/api/PetsApi.java => gen/java/io/swagger/api/PetApi.java} (58%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger/api}/RestApplication.java (81%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample/api/StoresApi.java => gen/java/io/swagger/api/StoreApi.java} (57%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample/api/UsersApi.java => gen/java/io/swagger/api/UserApi.java} (73%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger}/model/Category.java (85%) create mode 100644 samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger}/model/Order.java (73%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger}/model/Pet.java (73%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger}/model/Tag.java (85%) rename samples/server/petstore/jaxrs-spec/src/{main/java/com/ibm/ws/petstoresample => gen/java/io/swagger}/model/User.java (91%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index bc973ca97e3..b37e2860707 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -357,7 +357,7 @@ public class DefaultCodegen { // override with any special handling of the JMustache compiler @SuppressWarnings("unused") public Compiler processCompiler(Compiler compiler) { - return compiler; + return compiler; } // override with any special text escaping logic @@ -1708,7 +1708,7 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { property.isContainer = true; property.isListContainer = true; property.containerType = "array"; @@ -1719,7 +1719,7 @@ public class DefaultCodegen { property.minItems = ap.getMinItems(); CodegenProperty cp = fromProperty(property.name, ap.getItems()); updatePropertyForArray(property, cp); - } else if (p instanceof MapProperty) { + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1906,7 +1906,7 @@ public class DefaultCodegen { * @return Codegen Operation object */ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - return fromOperation(path, httpMethod, operation, definitions, null); + return fromOperation(path, httpMethod, operation, definitions, null); } /** @@ -2562,7 +2562,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { - return Collections.emptyList(); + return Collections.emptyList(); } List secs = new ArrayList(schemes.size()); @@ -2586,8 +2586,8 @@ public class DefaultCodegen { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); if (sec.flow == null) { @@ -3222,11 +3222,11 @@ public class DefaultCodegen { // encountered so far and hopefully make it easier for others to add more special // cases in the future. - // better error handling when map/array type is invalid - if (name == null) { - LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); - return "ERROR_UNKNOWN"; - } + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // if the name is just '$', map it to 'value' for the time being. if ("$".equals(name)) { @@ -3447,11 +3447,25 @@ public class DefaultCodegen { public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) { boolean booleanValue = false; if (additionalProperties.containsKey(propertyKey)) { - booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + booleanValue = convertPropertyToBoolean(propertyKey); // write back as boolean - additionalProperties.put(propertyKey, booleanValue); + writePropertyBack(propertyKey, booleanValue); } return booleanValue; } + + + public boolean convertPropertyToBoolean(String propertyKey) { + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + } + + return booleanValue; + } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 7c8d03c1375..74c2ccb0218 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -2,27 +2,31 @@ package io.swagger.codegen.languages; import java.io.File; import java.io.IOException; - import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.FileUtils; + import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import io.swagger.models.Swagger; +import io.swagger.models.properties.Property; import io.swagger.util.Json; -import org.apache.commons.io.FileUtils; -public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - public JavaJAXRSSpecServerCodegen() - { +public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen implements BeanValidationFeatures +{ + protected boolean useBeanValidation = true; + + public JavaJAXRSSpecServerCodegen() + { super(); invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; @@ -67,26 +71,37 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen library.setEnum(supportedLibraries); cliOptions.add(library); - } - - @Override - public void processOpts() - { - super.processOpts(); + + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + } + + @Override + public void processOpts() + { + super.processOpts(); + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } - supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); - } + } + - @Override - public String getName() - { - return "jaxrs-spec"; - } + @Override + public String getName() + { + return "jaxrs-spec"; + } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -127,16 +142,16 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen model.imports.remove("JsonProperty"); } - @Override + @Override public void preprocessSwagger(Swagger swagger) { - //copy input swagger to output folder - try { - String swaggerJson = Json.pretty(swagger); + //copy input swagger to output folder + try { + String swaggerJson = Json.pretty(swagger); FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); - } catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e.getMessage(), e.getCause()); - } - super.preprocessSwagger(swagger); + } + super.preprocessSwagger(swagger); } @Override @@ -144,4 +159,9 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { return "Generates a Java JAXRS Server according to JAXRS 2.0 specification."; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache index 5ffd9c2a6d3..088e254300b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache @@ -9,6 +9,9 @@ import javax.ws.rs.core.Response; import io.swagger.annotations.*; import java.util.List; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} @Path("/{{baseName}}") diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache index 1ef4a61efbe..a9d67c0471e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache @@ -1,16 +1,31 @@ -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; +public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + + private {{datatype}} value; + + {{datatypeWithEnum}} ({{datatype}} v) { + value = v; + } -@XmlType(name="{{classname}}") -@XmlEnum -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/allowableValues}} - public String value() { - return name(); + return value; } - public static {{classname}} fromValue(String v) { - return valueOf(v); + @Override + public String toString() { + return String.valueOf(value); } -} \ No newline at end of file + + public static {{datatypeWithEnum}} fromValue(String v) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache new file mode 100644 index 00000000000..85de81431b6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache @@ -0,0 +1,43 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache index b1036ceeb54..e88e3022aa7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@FormParam(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormParam(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, - @FormParam(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@FormParam(value = "{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormParam(value = "{{paramName}}") InputStream {{paramName}}InputStream, + @FormParam(value = "{{paramName}}") Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache index 49110fc1ad9..ad17a426e96 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache @@ -1 +1,3 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}} +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") +{{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache index 2c383a41a28..a93761806d2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache @@ -2,13 +2,18 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}}{{#description}} /** * {{description}} **/{{/description}} -{{#isEnum}}{{>enumClass}}{{/isEnum}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} {{^isEnum}}{{>pojo}}{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache index ba153467a65..f01e18d3523 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#description}} @ApiParam("{{description}}"){{/description}} {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache index d763209f030..4a0196046e2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -23,7 +23,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache index e65d27f8db4..cb92ea54823 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache @@ -69,6 +69,15 @@ + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache index be8cee8dfe1..11f78ddd90f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/jaxrs-spec/pom.xml b/samples/server/petstore/jaxrs-spec/pom.xml index c06fcab78d0..0c8ec37669a 100644 --- a/samples/server/petstore/jaxrs-spec/pom.xml +++ b/samples/server/petstore/jaxrs-spec/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - wasdev - autogen-server + io.swagger + swagger-jaxrs-server war - autogen-server + swagger-jaxrs-server 1.0.0 src/main/java @@ -69,6 +69,13 @@ + + + javax.validation + validation-api + 1.1.0.Final + provided + 4.8.1 diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java similarity index 58% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java index bb3beaf9f89..bbe6add41d6 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java @@ -1,140 +1,156 @@ -package com.ibm.ws.petstoresample.api; - -import com.ibm.ws.petstoresample.model.Pet; - -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import io.swagger.annotations.*; - -import java.util.List; - -@Path("/pets") - -@Api(description = "the pets API") - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") - -public class PetsApi { - - @POST - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response addPet(Pet body) { - return Response.ok().entity("magic!").build(); - } - - @DELETE - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet(@HeaderParam("api_key") String apiKey,@PathParam("petId") Long petId) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/findByStatus") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@QueryParam("status") List status) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/findByTags") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), - @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@QueryParam("tags") List tags) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/{petId}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }), - @Authorization(value = "api_key") - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), - @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@PathParam("petId") Long petId) { - return Response.ok().entity("magic!").build(); - } - - @PUT - - @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet", }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - @ApiResponse(code = 404, message = "Pet not found", response = void.class), - @ApiResponse(code = 405, message = "Validation exception", response = void.class) }) - public Response updatePet(Pet body) { - return Response.ok().entity("magic!").build(); - } - - @POST - @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }) - }, tags={ "pet" }) - @ApiResponses(value = { - @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@PathParam("petId") String petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { - return Response.ok().entity("magic!").build(); - } -} - +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import io.swagger.annotations.*; + +import java.util.List; +import javax.validation.constraints.*; + +@Path("/pet") + +@Api(description = "the pet API") + + + + +public class PetApi { + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response addPet(Pet body) { + return Response.ok().entity("magic!").build(); + } + + @DELETE + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) + public Response deletePet(@PathParam("petId") @ApiParam("Pet id to delete") Long petId,@HeaderParam("api_key") String apiKey) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/findByStatus") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByStatus(@QueryParam("status") @NotNull List status) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/findByTags") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) + public Response findPetsByTags(@QueryParam("tags") @NotNull List tags) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/{petId}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + public Response getPetById(@PathParam("petId") @ApiParam("ID of pet to return") Long petId) { + return Response.ok().entity("magic!").build(); + } + + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @ApiResponse(code = 404, message = "Pet not found", response = void.class), + @ApiResponse(code = 405, message = "Validation exception", response = void.class) }) + public Response updatePet(Pet body) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public Response updatePetWithForm(@PathParam("petId") @ApiParam("ID of pet that needs to be updated") Long petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@PathParam("petId") @ApiParam("ID of pet to update") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream fileInputStream, + @FormParam(value = "file") Attachment fileDetail) { + return Response.ok().entity("magic!").build(); + } +} + diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java similarity index 81% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java index 9c43b1e80ba..56e801bbf5f 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java @@ -1,4 +1,4 @@ -package com.ibm.ws.petstoresample; +package io.swagger.api; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java similarity index 57% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java index 4f7613eed27..e8ff3d49e80 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java @@ -1,58 +1,73 @@ -package com.ibm.ws.petstoresample.api; - -import com.ibm.ws.petstoresample.model.Order; - -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import io.swagger.annotations.*; - -import java.util.List; - -@Path("/stores") - -@Api(description = "the stores API") - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") - -public class StoresApi { - - @DELETE - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), - @ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder(@PathParam("orderId") String orderId) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/order/{orderId}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Order.class), - @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), - @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@PathParam("orderId") String orderId) { - return Response.ok().entity("magic!").build(); - } - - @POST - @Path("/order") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Order.class), - @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder(Order body) { - return Response.ok().entity("magic!").build(); - } -} - +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import io.swagger.annotations.*; + +import java.util.List; +import javax.validation.constraints.*; + +@Path("/store") + +@Api(description = "the store API") + + + + +public class StoreApi { + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), + @ApiResponse(code = 404, message = "Order not found", response = void.class) }) + public Response deleteOrder(@PathParam("orderId") @Min(1) @ApiParam("ID of the order that needs to be deleted") String orderId) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory() { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/order/{orderId}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + public Response getOrderById(@PathParam("orderId") @Min(1) @Max(5) @ApiParam("ID of pet that needs to be fetched") Long orderId) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/order") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + public Response placeOrder(Order body) { + return Response.ok().entity("magic!").build(); + } +} + diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java similarity index 73% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java index 4bf8701edbf..fb6b92e2514 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java @@ -1,115 +1,116 @@ -package com.ibm.ws.petstoresample.api; - -import com.ibm.ws.petstoresample.model.User; -import java.util.List; - -import javax.ws.rs.*; -import javax.ws.rs.core.Response; - -import io.swagger.annotations.*; - -import java.util.List; - -@Path("/users") - -@Api(description = "the users API") - - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") - -public class UsersApi { - - @POST - - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUser(User body) { - return Response.ok().entity("magic!").build(); - } - - @POST - @Path("/createWithArray") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithArrayInput(List body) { - return Response.ok().entity("magic!").build(); - } - - @POST - @Path("/createWithList") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response createUsersWithListInput(List body) { - return Response.ok().entity("magic!").build(); - } - - @DELETE - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), - @ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser(@PathParam("username") String username) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = User.class), - @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), - @ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@PathParam("username") String username) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/login") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = String.class), - @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password) { - return Response.ok().entity("magic!").build(); - } - - @GET - @Path("/logout") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) - @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = void.class) }) - public Response logoutUser() { - return Response.ok().entity("magic!").build(); - } - - @PUT - @Path("/{username}") - - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) - @ApiResponses(value = { - @ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), - @ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser(@PathParam("username") String username,User body) { - return Response.ok().entity("magic!").build(); - } -} - +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import io.swagger.annotations.*; + +import java.util.List; +import javax.validation.constraints.*; + +@Path("/user") + +@Api(description = "the user API") + + + + +public class UserApi { + + @POST + + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUser(User body) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/createWithArray") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithArrayInput(List body) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/createWithList") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response createUsersWithListInput(List body) { + return Response.ok().entity("magic!").build(); + } + + @DELETE + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response deleteUser(@PathParam("username") @ApiParam("The name that needs to be deleted") String username) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + public Response getUserByName(@PathParam("username") @ApiParam("The name that needs to be fetched. Use user1 for testing. ") String username) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/login") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + public Response loginUser(@QueryParam("username") @NotNull String username,@QueryParam("password") @NotNull String password) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/logout") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = void.class) }) + public Response logoutUser() { + return Response.ok().entity("magic!").build(); + } + + @PUT + @Path("/{username}") + + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), + @ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response updateUser(@PathParam("username") @ApiParam("name that need to be deleted") String username,User body) { + return Response.ok().entity("magic!").build(); + } +} + diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java similarity index 85% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java index cef2cf7ff95..a382801bdba 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java @@ -1,87 +1,91 @@ -package com.ibm.ws.petstoresample.model; - - - - -import io.swagger.annotations.*; -import java.util.Objects; - - -public class Category { - - private Long id = null; - private String name = null; - - /** - **/ - public Category id(Long id) { - this.id = id; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - public Category name(String name) { - this.name = name; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * A category for a pet + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A category for a pet") + +public class Category { + + private Long id = null; + private String name = null; + + /** + **/ + public Category id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Category name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..20e0effb560 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * Describes the result of uploading an image resource + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Describes the result of uploading an image resource") + +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java similarity index 73% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java index ce7995e3437..be4f4c54b69 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java @@ -1,164 +1,199 @@ -package com.ibm.ws.petstoresample.model; - - - - -import io.swagger.annotations.*; -import java.util.Objects; - - -public class Order { - - private Long id = null; - private Long petId = null; - private Integer quantity = null; - private javax.xml.datatype.XMLGregorianCalendar shipDate = null; - private String status = null; - private Boolean complete = null; - - /** - **/ - public Order id(Long id) { - this.id = id; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - public Order petId(Long petId) { - this.petId = petId; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - /** - **/ - public Order quantity(Integer quantity) { - this.quantity = quantity; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - /** - **/ - public Order shipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { - this.shipDate = shipDate; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public javax.xml.datatype.XMLGregorianCalendar getShipDate() { - return shipDate; - } - public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { - this.shipDate = shipDate; - } - - /** - * Order Status - **/ - public Order status(String status) { - this.status = status; - return this; - } - - - @ApiModelProperty(example = "null", value = "Order Status") - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - - /** - **/ - public Order complete(Boolean complete) { - this.complete = complete; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); - } - - @Override - public int hashCode() { - return Objects.hash(id, petId, quantity, shipDate, status, complete); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); - sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); - sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * An order for a pets from the pet store + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "An order for a pets from the pet store") + +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private javax.xml.datatype.XMLGregorianCalendar shipDate = null; + +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private StatusEnum status = null; + private Boolean complete = false; + + /** + **/ + public Order id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + /** + **/ + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + /** + **/ + public Order shipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public javax.xml.datatype.XMLGregorianCalendar getShipDate() { + return shipDate; + } + public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + } + + /** + * Order Status + **/ + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + /** + **/ + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java similarity index 73% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java index 30e81e1c988..30114aa1817 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java @@ -1,168 +1,205 @@ -package com.ibm.ws.petstoresample.model; - -import com.ibm.ws.petstoresample.model.Category; -import com.ibm.ws.petstoresample.model.Tag; -import java.util.ArrayList; -import java.util.List; - - - -import io.swagger.annotations.*; -import java.util.Objects; - - -public class Pet { - - private Long id = null; - private Category category = null; - private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); - private String status = null; - - /** - **/ - public Pet id(Long id) { - this.id = id; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - public Pet category(Category category) { - this.category = category; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - /** - **/ - public Pet name(String name) { - this.name = name; - return this; - } - - - @ApiModelProperty(example = "doggie", required = true, value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - /** - **/ - public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; - return this; - } - - - @ApiModelProperty(example = "null", required = true, value = "") - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - /** - **/ - public Pet tags(List tags) { - this.tags = tags; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - /** - * pet status in the store - **/ - public Pet status(String status) { - this.status = status; - return this; - } - - - @ApiModelProperty(example = "null", value = "pet status in the store") - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); - } - - @Override - public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" category: ").append(toIndentedString(category)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); - sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); - sb.append(" status: ").append(toIndentedString(status)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +/** + * A pet for sale in the pet store + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A pet for sale in the pet store") + +public class Pet { + + private Long id = null; + private Category category = null; + private String name = null; + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); + +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private StatusEnum status = null; + + /** + **/ + public Pet id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Pet category(Category category) { + this.category = category; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + /** + **/ + public Pet name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + /** + **/ + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + /** + **/ + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + /** + * pet status in the store + **/ + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + @ApiModelProperty(example = "null", value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java similarity index 85% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java index 351770bd7c5..d99f85caac0 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java @@ -1,87 +1,91 @@ -package com.ibm.ws.petstoresample.model; - - - - -import io.swagger.annotations.*; -import java.util.Objects; - - -public class Tag { - - private Long id = null; - private String name = null; - - /** - **/ - public Tag id(Long id) { - this.id = id; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - public Tag name(String name) { - this.name = name; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); - } - - @Override - public int hashCode() { - return Objects.hash(id, name); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" name: ").append(toIndentedString(name)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * A tag for a pet + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A tag for a pet") + +public class Tag { + + private Long id = null; + private String name = null; + + /** + **/ + public Tag id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public Tag name(String name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java similarity index 91% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java index 22369ba154d..b249ee61027 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java @@ -1,202 +1,206 @@ -package com.ibm.ws.petstoresample.model; - - - - -import io.swagger.annotations.*; -import java.util.Objects; - - -public class User { - - private Long id = null; - private String username = null; - private String firstName = null; - private String lastName = null; - private String email = null; - private String password = null; - private String phone = null; - private Integer userStatus = null; - - /** - **/ - public User id(Long id) { - this.id = id; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - /** - **/ - public User username(String username) { - this.username = username; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - /** - **/ - public User firstName(String firstName) { - this.firstName = firstName; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - /** - **/ - public User lastName(String lastName) { - this.lastName = lastName; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - /** - **/ - public User email(String email) { - this.email = email; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - /** - **/ - public User password(String password) { - this.password = password; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - /** - **/ - public User phone(String phone) { - this.phone = phone; - return this; - } - - - @ApiModelProperty(example = "null", value = "") - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - /** - * User Status - **/ - public User userStatus(Integer userStatus) { - this.userStatus = userStatus; - return this; - } - - - @ApiModelProperty(example = "null", value = "User Status") - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); - } - - @Override - public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(toIndentedString(id)).append("\n"); - sb.append(" username: ").append(toIndentedString(username)).append("\n"); - sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); - sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); - sb.append(" email: ").append(toIndentedString(email)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); - sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); - sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); - sb.append("}"); - return sb.toString(); - } - - /** - * Convert the given object to string with each line indented by 4 spaces - * (except the first line). - */ - private String toIndentedString(Object o) { - if (o == null) { - return "null"; - } - return o.toString().replace("\n", "\n "); - } -} +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * A User who is purchasing from the pet store + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "A User who is purchasing from the pet store") + +public class User { + + private Long id = null; + private String username = null; + private String firstName = null; + private String lastName = null; + private String email = null; + private String password = null; + private String phone = null; + private Integer userStatus = null; + + /** + **/ + public User id(Long id) { + this.id = id; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + /** + **/ + public User username(String username) { + this.username = username; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + /** + **/ + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + /** + **/ + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + /** + **/ + public User email(String email) { + this.email = email; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + /** + **/ + public User password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + /** + **/ + public User phone(String phone) { + this.phone = phone; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + /** + * User Status + **/ + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + @ApiModelProperty(example = "null", value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/swagger.json b/samples/server/petstore/jaxrs-spec/swagger.json index 4524933cd36..a3adac3d4ac 100644 --- a/samples/server/petstore/jaxrs-spec/swagger.json +++ b/samples/server/petstore/jaxrs-spec/swagger.json @@ -1,674 +1,831 @@ -{ - "swagger" : "2.0", - "info" : { - "description" : "This is a sample server Petstore server.\n\n[Learn about Swagger](http://swagger.io) or join the IRC channel `#swagger` on irc.freenode.net.\n\nFor this sample, you can use the api key `special-key` to test the authorization filters\n", - "version" : "1.0.0", - "title" : "Swagger Petstore", - "termsOfService" : "http://helloreverb.com/terms/", - "contact" : { - "name" : "apiteam@swagger.io" - }, - "license" : { - "name" : "Apache 2.0", - "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "host" : "petstore.swagger.io", - "basePath" : "/v2", - "schemes" : [ "http" ], - "paths" : { - "/pets" : { - "post" : { - "tags" : [ "pet" ], - "summary" : "Add a new pet to the store", - "description" : "", - "operationId" : "addPet", - "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } - } ], - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - }, - "put" : { - "tags" : [ "pet" ], - "summary" : "Update an existing pet", - "description" : "", - "operationId" : "updatePet", - "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Pet object that needs to be added to the store", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Pet" - } - } ], - "responses" : { - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - }, - "405" : { - "description" : "Validation exception" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - } - }, - "/pets/findByStatus" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Finds Pets by status", - "description" : "Multiple status values can be provided with comma separated strings", - "operationId" : "findPetsByStatus", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "status", - "in" : "query", - "description" : "Status values that need to be considered for filter", - "required" : false, - "type" : "array", - "items" : { - "type" : "string" - }, - "collectionFormat" : "multi" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } - }, - "400" : { - "description" : "Invalid status value" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - } - }, - "/pets/findByTags" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Finds Pets by tags", - "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", - "operationId" : "findPetsByTags", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "tags", - "in" : "query", - "description" : "Tags to filter by", - "required" : false, - "type" : "array", - "items" : { - "type" : "string" - }, - "collectionFormat" : "multi" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Pet" - } - } - }, - "400" : { - "description" : "Invalid tag value" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - } - }, - "/pets/{petId}" : { - "get" : { - "tags" : [ "pet" ], - "summary" : "Find pet by ID", - "description" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", - "operationId" : "getPetById", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "integer", - "format" : "int64" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Pet" - } - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Pet not found" - } - }, - "security" : [ { - "api_key" : [ ] - }, { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - }, - "post" : { - "tags" : [ "pet" ], - "summary" : "Updates a pet in the store with form data", - "description" : "", - "operationId" : "updatePetWithForm", - "consumes" : [ "application/x-www-form-urlencoded" ], - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "petId", - "in" : "path", - "description" : "ID of pet that needs to be updated", - "required" : true, - "type" : "string" - }, { - "name" : "name", - "in" : "formData", - "description" : "Updated name of the pet", - "required" : true, - "type" : "string" - }, { - "name" : "status", - "in" : "formData", - "description" : "Updated status of the pet", - "required" : true, - "type" : "string" - } ], - "responses" : { - "405" : { - "description" : "Invalid input" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - }, - "delete" : { - "tags" : [ "pet" ], - "summary" : "Deletes a pet", - "description" : "", - "operationId" : "deletePet", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "api_key", - "in" : "header", - "description" : "", - "required" : true, - "type" : "string" - }, { - "name" : "petId", - "in" : "path", - "description" : "Pet id to delete", - "required" : true, - "type" : "integer", - "format" : "int64" - } ], - "responses" : { - "400" : { - "description" : "Invalid pet value" - } - }, - "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] - } ] - } - }, - "/stores/order" : { - "post" : { - "tags" : [ "store" ], - "summary" : "Place an order for a pet", - "description" : "", - "operationId" : "placeOrder", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "order placed for purchasing the pet", - "required" : false, - "schema" : { - "$ref" : "#/definitions/Order" - } - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } - }, - "400" : { - "description" : "Invalid Order" - } - } - } - }, - "/stores/order/{orderId}" : { - "get" : { - "tags" : [ "store" ], - "summary" : "Find purchase order by ID", - "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", - "operationId" : "getOrderById", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "orderId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "string" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/Order" - } - }, - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - } - }, - "delete" : { - "tags" : [ "store" ], - "summary" : "Delete purchase order by ID", - "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "operationId" : "deleteOrder", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "orderId", - "in" : "path", - "description" : "ID of the order that needs to be deleted", - "required" : true, - "type" : "string" - } ], - "responses" : { - "400" : { - "description" : "Invalid ID supplied" - }, - "404" : { - "description" : "Order not found" - } - } - } - }, - "/users" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Create user", - "description" : "This can only be done by the logged in user.", - "operationId" : "createUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "Created user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/users/createWithArray" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Creates list of users with given input array", - "description" : "", - "operationId" : "createUsersWithArrayInput", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/users/createWithList" : { - "post" : { - "tags" : [ "user" ], - "summary" : "Creates list of users with given input array", - "description" : "", - "operationId" : "createUsersWithListInput", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "in" : "body", - "name" : "body", - "description" : "List of user object", - "required" : false, - "schema" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/User" - } - } - } ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/users/login" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Logs user into the system", - "description" : "", - "operationId" : "loginUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "query", - "description" : "The user name for login", - "required" : false, - "type" : "string" - }, { - "name" : "password", - "in" : "query", - "description" : "The password for login in clear text", - "required" : false, - "type" : "string" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "type" : "string" - } - }, - "400" : { - "description" : "Invalid username/password supplied" - } - } - } - }, - "/users/logout" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Logs out current logged in user session", - "description" : "", - "operationId" : "logoutUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ ], - "responses" : { - "default" : { - "description" : "successful operation" - } - } - } - }, - "/users/{username}" : { - "get" : { - "tags" : [ "user" ], - "summary" : "Get user by user name", - "description" : "", - "operationId" : "getUserByName", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing.", - "required" : true, - "type" : "string" - } ], - "responses" : { - "200" : { - "description" : "successful operation", - "schema" : { - "$ref" : "#/definitions/User" - } - }, - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - } - }, - "put" : { - "tags" : [ "user" ], - "summary" : "Updated user", - "description" : "This can only be done by the logged in user.", - "operationId" : "updateUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "name that need to be deleted", - "required" : true, - "type" : "string" - }, { - "in" : "body", - "name" : "body", - "description" : "Updated user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } - } ], - "responses" : { - "400" : { - "description" : "Invalid user supplied" - }, - "404" : { - "description" : "User not found" - } - } - }, - "delete" : { - "tags" : [ "user" ], - "summary" : "Delete user", - "description" : "This can only be done by the logged in user.", - "operationId" : "deleteUser", - "produces" : [ "application/json", "application/xml" ], - "parameters" : [ { - "name" : "username", - "in" : "path", - "description" : "The name that needs to be deleted", - "required" : true, - "type" : "string" - } ], - "responses" : { - "400" : { - "description" : "Invalid username supplied" - }, - "404" : { - "description" : "User not found" - } - } - } - } - }, - "securityDefinitions" : { - "petstore_auth" : { - "type" : "oauth2", - "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", - "flow" : "implicit", - "scopes" : { - "write_pets" : "modify pets in your account", - "read_pets" : "read your pets" - } - }, - "api_key" : { - "type" : "apiKey", - "name" : "api_key", - "in" : "header" - } - }, - "definitions" : { - "User" : { - "type" : "object", - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "username" : { - "type" : "string" - }, - "firstName" : { - "type" : "string" - }, - "lastName" : { - "type" : "string" - }, - "email" : { - "type" : "string" - }, - "password" : { - "type" : "string" - }, - "phone" : { - "type" : "string" - }, - "userStatus" : { - "type" : "integer", - "format" : "int32", - "description" : "User Status" - } - } - }, - "Category" : { - "type" : "object", - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - } - }, - "Pet" : { - "type" : "object", - "required" : [ "name", "photoUrls" ], - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "category" : { - "$ref" : "#/definitions/Category" - }, - "name" : { - "type" : "string", - "example" : "doggie" - }, - "photoUrls" : { - "type" : "array", - "items" : { - "type" : "string" - } - }, - "tags" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Tag" - } - }, - "status" : { - "type" : "string", - "description" : "pet status in the store" - } - } - }, - "Tag" : { - "type" : "object", - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - } - }, - "Order" : { - "type" : "object", - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "petId" : { - "type" : "integer", - "format" : "int64" - }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "shipDate" : { - "type" : "string", - "format" : "date-time" - }, - "status" : { - "type" : "string", - "description" : "Order Status" - }, - "complete" : { - "type" : "boolean" - } - } - } - } +{ + "swagger" : "2.0", + "info" : { + "description" : "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version" : "1.0.0", + "title" : "Swagger Petstore", + "termsOfService" : "http://swagger.io/terms/", + "contact" : { + "email" : "apiteam@swagger.io" + }, + "license" : { + "name" : "Apache 2.0", + "url" : "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host" : "petstore.swagger.io", + "basePath" : "/v2", + "tags" : [ { + "name" : "pet", + "description" : "Everything about your Pets", + "externalDocs" : { + "description" : "Find out more", + "url" : "http://swagger.io" + } + }, { + "name" : "store", + "description" : "Access to Petstore orders" + }, { + "name" : "user", + "description" : "Operations about user", + "externalDocs" : { + "description" : "Find out more about our store", + "url" : "http://swagger.io" + } + } ], + "schemes" : [ "http" ], + "paths" : { + "/pet" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "Add a new pet to the store", + "description" : "", + "operationId" : "addPet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "put" : { + "tags" : [ "pet" ], + "summary" : "Update an existing pet", + "description" : "", + "operationId" : "updatePet", + "consumes" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Pet object that needs to be added to the store", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Pet" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + }, + "405" : { + "description" : "Validation exception" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/findByStatus" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by status", + "description" : "Multiple status values can be provided with comma separated strings", + "operationId" : "findPetsByStatus", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "status", + "in" : "query", + "description" : "Status values that need to be considered for filter", + "required" : true, + "type" : "array", + "items" : { + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid status value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/findByTags" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Finds Pets by tags", + "description" : "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId" : "findPetsByTags", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "tags", + "in" : "query", + "description" : "Tags to filter by", + "required" : true, + "type" : "array", + "items" : { + "type" : "string" + }, + "collectionFormat" : "csv" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Pet" + } + } + }, + "400" : { + "description" : "Invalid tag value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}" : { + "get" : { + "tags" : [ "pet" ], + "summary" : "Find pet by ID", + "description" : "Returns a single pet", + "operationId" : "getPetById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to return", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Pet" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Pet not found" + } + }, + "security" : [ { + "api_key" : [ ] + } ] + }, + "post" : { + "tags" : [ "pet" ], + "summary" : "Updates a pet in the store with form data", + "description" : "", + "operationId" : "updatePetWithForm", + "consumes" : [ "application/x-www-form-urlencoded" ], + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet that needs to be updated", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "name", + "in" : "formData", + "description" : "Updated name of the pet", + "required" : false, + "type" : "string" + }, { + "name" : "status", + "in" : "formData", + "description" : "Updated status of the pet", + "required" : false, + "type" : "string" + } ], + "responses" : { + "405" : { + "description" : "Invalid input" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + }, + "delete" : { + "tags" : [ "pet" ], + "summary" : "Deletes a pet", + "description" : "", + "operationId" : "deletePet", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "api_key", + "in" : "header", + "required" : false, + "type" : "string" + }, { + "name" : "petId", + "in" : "path", + "description" : "Pet id to delete", + "required" : true, + "type" : "integer", + "format" : "int64" + } ], + "responses" : { + "400" : { + "description" : "Invalid pet value" + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/pet/{petId}/uploadImage" : { + "post" : { + "tags" : [ "pet" ], + "summary" : "uploads an image", + "description" : "", + "operationId" : "uploadFile", + "consumes" : [ "multipart/form-data" ], + "produces" : [ "application/json" ], + "parameters" : [ { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to update", + "required" : true, + "type" : "integer", + "format" : "int64" + }, { + "name" : "additionalMetadata", + "in" : "formData", + "description" : "Additional data to pass to server", + "required" : false, + "type" : "string" + }, { + "name" : "file", + "in" : "formData", + "description" : "file to upload", + "required" : false, + "type" : "file" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/ApiResponse" + } + } + }, + "security" : [ { + "petstore_auth" : [ "write:pets", "read:pets" ] + } ] + } + }, + "/store/inventory" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Returns pet inventories by status", + "description" : "Returns a map of status codes to quantities", + "operationId" : "getInventory", + "produces" : [ "application/json" ], + "parameters" : [ ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "object", + "additionalProperties" : { + "type" : "integer", + "format" : "int32" + } + } + } + }, + "security" : [ { + "api_key" : [ ] + } ] + } + }, + "/store/order" : { + "post" : { + "tags" : [ "store" ], + "summary" : "Place an order for a pet", + "description" : "", + "operationId" : "placeOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "order placed for purchasing the pet", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Order" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid Order" + } + } + } + }, + "/store/order/{orderId}" : { + "get" : { + "tags" : [ "store" ], + "summary" : "Find purchase order by ID", + "description" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId" : "getOrderById", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of pet that needs to be fetched", + "required" : true, + "type" : "integer", + "maximum" : 5, + "minimum" : 1, + "format" : "int64" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } + }, + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + } + }, + "delete" : { + "tags" : [ "store" ], + "summary" : "Delete purchase order by ID", + "description" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId" : "deleteOrder", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string", + "minimum" : 1 + } ], + "responses" : { + "400" : { + "description" : "Invalid ID supplied" + }, + "404" : { + "description" : "Order not found" + } + } + } + }, + "/user" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Create user", + "description" : "This can only be done by the logged in user.", + "operationId" : "createUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/createWithArray" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithArrayInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/createWithList" : { + "post" : { + "tags" : [ "user" ], + "summary" : "Creates list of users with given input array", + "description" : "", + "operationId" : "createUsersWithListInput", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "List of user object", + "required" : true, + "schema" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/User" + } + } + } ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/login" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs user into the system", + "description" : "", + "operationId" : "loginUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : true, + "type" : "string" + }, { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "type" : "string" + }, + "headers" : { + "X-Rate-Limit" : { + "type" : "integer", + "format" : "int32", + "description" : "calls per hour allowed by the user" + }, + "X-Expires-After" : { + "type" : "string", + "format" : "date-time", + "description" : "date in UTC when toekn expires" + } + } + }, + "400" : { + "description" : "Invalid username/password supplied" + } + } + } + }, + "/user/logout" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Logs out current logged in user session", + "description" : "", + "operationId" : "logoutUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ ], + "responses" : { + "default" : { + "description" : "successful operation" + } + } + } + }, + "/user/{username}" : { + "get" : { + "tags" : [ "user" ], + "summary" : "Get user by user name", + "description" : "", + "operationId" : "getUserByName", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be fetched. Use user1 for testing. ", + "required" : true, + "type" : "string" + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/User" + } + }, + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + } + }, + "put" : { + "tags" : [ "user" ], + "summary" : "Updated user", + "description" : "This can only be done by the logged in user.", + "operationId" : "updateUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "name that need to be deleted", + "required" : true, + "type" : "string" + }, { + "in" : "body", + "name" : "body", + "description" : "Updated user object", + "required" : true, + "schema" : { + "$ref" : "#/definitions/User" + } + } ], + "responses" : { + "400" : { + "description" : "Invalid user supplied" + }, + "404" : { + "description" : "User not found" + } + } + }, + "delete" : { + "tags" : [ "user" ], + "summary" : "Delete user", + "description" : "This can only be done by the logged in user.", + "operationId" : "deleteUser", + "produces" : [ "application/xml", "application/json" ], + "parameters" : [ { + "name" : "username", + "in" : "path", + "description" : "The name that needs to be deleted", + "required" : true, + "type" : "string" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + } + } + } + }, + "securityDefinitions" : { + "petstore_auth" : { + "type" : "oauth2", + "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", + "flow" : "implicit", + "scopes" : { + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" + } + }, + "api_key" : { + "type" : "apiKey", + "name" : "api_key", + "in" : "header" + } + }, + "definitions" : { + "Order" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "petId" : { + "type" : "integer", + "format" : "int64" + }, + "quantity" : { + "type" : "integer", + "format" : "int32" + }, + "shipDate" : { + "type" : "string", + "format" : "date-time" + }, + "status" : { + "type" : "string", + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ] + }, + "complete" : { + "type" : "boolean", + "default" : false + } + }, + "title" : "Pet Order", + "description" : "An order for a pets from the pet store", + "xml" : { + "name" : "Order" + } + }, + "Category" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet catehgry", + "description" : "A category for a pet", + "xml" : { + "name" : "Category" + } + }, + "User" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "username" : { + "type" : "string" + }, + "firstName" : { + "type" : "string" + }, + "lastName" : { + "type" : "string" + }, + "email" : { + "type" : "string" + }, + "password" : { + "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "type" : "integer", + "format" : "int32", + "description" : "User Status" + } + }, + "title" : "a User", + "description" : "A User who is purchasing from the pet store", + "xml" : { + "name" : "User" + } + }, + "Tag" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "title" : "Pet Tag", + "description" : "A tag for a pet", + "xml" : { + "name" : "Tag" + } + }, + "Pet" : { + "type" : "object", + "required" : [ "name", "photoUrls" ], + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "category" : { + "$ref" : "#/definitions/Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } + }, + "status" : { + "type" : "string", + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "title" : "a Pet", + "description" : "A pet for sale in the pet store", + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" + }, + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" + } + }, + "title" : "An uploaded response", + "description" : "Describes the result of uploading an image resource" + } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" + } } \ No newline at end of file From ccecc2aac038cd5fcaa1aab9128cd9c09266da32 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 19 Jan 2017 15:31:24 +0800 Subject: [PATCH 264/269] new file for jaxrs jersey1 --- .../java/io/swagger/model/Capitalization.java | 210 ++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..8e880223f76 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,210 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @JsonProperty("smallCamel") + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @JsonProperty("CapitalCamel") + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @JsonProperty("small_Snake") + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @JsonProperty("Capital_Snake") + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @JsonProperty("SCA_ETH_Flow_Points") + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @JsonProperty("ATT_NAME") + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + From a8afaa8f77575c5147d5ead749cea7cfff210177 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 19 Jan 2017 15:53:51 +0800 Subject: [PATCH 265/269] remove /r from templates --- .../resources/JavaJaxRS/apiService.mustache | 56 +++---- .../JavaJaxRS/apiServiceImpl.mustache | 64 ++++---- .../JavaJaxRS/beanValidation.mustache | 104 ++++++------- .../libraries/jersey1/apiService.mustache | 64 ++++---- .../libraries/jersey1/apiServiceImpl.mustache | 72 ++++----- .../java/io/swagger/api/FakeApiService.java | 62 ++++---- .../java/io/swagger/api/PetApiService.java | 82 +++++----- .../java/io/swagger/api/StoreApiService.java | 64 ++++---- .../java/io/swagger/api/UserApiService.java | 80 +++++----- .../src/gen/java/io/swagger/model/Animal.java | 2 +- .../gen/java/io/swagger/model/FormatTest.java | 32 ++-- .../src/gen/java/io/swagger/model/Name.java | 2 +- .../src/gen/java/io/swagger/model/Pet.java | 4 +- .../swagger/api/impl/FakeApiServiceImpl.java | 86 +++++------ .../swagger/api/impl/PetApiServiceImpl.java | 146 +++++++++--------- .../swagger/api/impl/StoreApiServiceImpl.java | 96 ++++++------ .../swagger/api/impl/UserApiServiceImpl.java | 144 ++++++++--------- 17 files changed, 580 insertions(+), 580 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 6fe60bcf862..eb8d9aaaa02 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -1,28 +1,28 @@ -package {{package}}; - -import {{package}}.*; -import {{modelPackage}}.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{>generatedAnnotation}} -{{#operations}} -public abstract class {{classname}}Service { - {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; - {{/operation}} -} -{{/operations}} +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 23adf05ec80..bc577e6f609 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -1,32 +1,32 @@ -package {{package}}.impl; - -import {{package}}.*; -import {{modelPackage}}.*; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{>generatedAnnotation}} -{{#operations}} -public class {{classname}}ServiceImpl extends {{classname}}Service { - {{#operation}} - @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - {{/operation}} -} -{{/operations}} +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache index eead16d7d98..079eab89d1a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache @@ -1,53 +1,53 @@ -{{#required}} - @NotNull -{{/required}} -{{#pattern}} - @Pattern(regexp="{{pattern}}") -{{/pattern}} -{{#minLength}} -{{#maxLength}} - @Size(min={{minLength}},max={{maxLength}}) -{{/maxLength}} -{{/minLength}} -{{#minLength}} -{{^maxLength}} - @Size(min={{minLength}}) -{{/maxLength}} -{{/minLength}} -{{^minLength}} -{{#maxLength}} - @Size(max={{maxLength}}) - {{/maxLength}} - {{/minLength}} -{{#minItems}} -{{#maxItems}} - @Size(min={{minItems}},max={{maxItems}}) -{{/maxItems}} -{{/minItems}} -{{#minItems}} -{{^maxItems}} - @Size(min={{minItems}}) -{{/maxItems}} -{{/minItems}} -{{^minItems}} -{{#maxItems}} - @Size(max={{maxItems}}) -{{/maxItems}} -{{/minItems}} -{{! check for integer / number=decimal type}} -{{#isInteger}} -{{#minimum}} - @Min({{minimum}}) -{{/minimum}} -{{#maximum}} - @Max({{maximum}}) -{{/maximum}} -{{/isInteger}} -{{^isInteger}} -{{#minimum}} - @DecimalMin("{{minimum}}") -{{/minimum}} -{{#maximum}} - @DecimalMax("{{maximum}}") -{{/maximum}} +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} {{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache index e1936698d02..0d3ab0ebe17 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache @@ -1,32 +1,32 @@ -package {{package}}; - -import {{package}}.*; -import {{modelPackage}}.*; - -import com.sun.jersey.multipart.FormDataParam; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{>generatedAnnotation}} -{{#operations}} -public abstract class {{classname}}Service { - {{#operation}} - public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) - throws NotFoundException; - {{/operation}} -} -{{/operations}} +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public abstract class {{classname}}Service { + {{#operation}} + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}},{{/allParams}}SecurityContext securityContext) + throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache index ac7c6096b24..abe789f1cbf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache @@ -1,36 +1,36 @@ -package {{package}}.impl; - -import {{package}}.*; -import {{modelPackage}}.*; - -import com.sun.jersey.multipart.FormDataParam; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{>generatedAnnotation}} -{{#operations}} -public class {{classname}}ServiceImpl extends {{classname}}Service { - {{#operation}} - @Override - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - {{/operation}} -} -{{/operations}} +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}}ServiceImpl extends {{classname}}Service { + {{#operation}} + @Override + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}, {{/allParams}}SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java index 247c18519b9..0714ed3f02a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java @@ -1,31 +1,31 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class FakeApiService { - public abstract Response testClientModel(Client body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) - throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) + throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index de4c7a63456..62be64f485f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -1,41 +1,41 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class PetApiService { - public abstract Response addPet(Pet body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) - throws NotFoundException; - public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) - throws NotFoundException; - public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getPetById(Long petId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updatePet(Pet body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) - throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class PetApiService { + public abstract Response addPet(Pet body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) + throws NotFoundException; + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) + throws NotFoundException; + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getPetById(Long petId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response updatePet(Pet body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) + throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java index 5e9320deccd..283e2687eb2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java @@ -1,32 +1,32 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class StoreApiService { - public abstract Response deleteOrder( @Min(1.0)String orderId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getInventory(SecurityContext securityContext) - throws NotFoundException; - public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) - throws NotFoundException; - public abstract Response placeOrder(Order body,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class StoreApiService { + public abstract Response deleteOrder( @Min(1.0)String orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) + throws NotFoundException; + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) + throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java index 7c739c6890b..81d2eebcacf 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java @@ -1,40 +1,40 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class UserApiService { - public abstract Response createUser(User body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) - throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) - throws NotFoundException; - public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) - throws NotFoundException; - public abstract Response logoutUser(SecurityContext securityContext) - throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) - throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class UserApiService { + public abstract Response createUser(User body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) + throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response getUserByName(String username,SecurityContext securityContext) + throws NotFoundException; + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) + throws NotFoundException; + public abstract Response logoutUser(SecurityContext securityContext) + throws NotFoundException; + public abstract Response updateUser(String username,User body,SecurityContext securityContext) + throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java index ff2a4f034eb..1898c8254e0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java @@ -44,7 +44,7 @@ public class Animal { **/ @JsonProperty("className") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public String getClassName() { return className; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java index a2a748a08d7..973afef18fe 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -79,8 +79,8 @@ public class FormatTest { **/ @JsonProperty("integer") @ApiModelProperty(value = "") - @Min(10) - @Max(100) + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -102,8 +102,8 @@ public class FormatTest { **/ @JsonProperty("int32") @ApiModelProperty(value = "") - @Min(20) - @Max(200) + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -144,9 +144,9 @@ public class FormatTest { **/ @JsonProperty("number") @ApiModelProperty(required = true, value = "") - @NotNull - @DecimalMin("32.1") - @DecimalMax("543.2") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -168,8 +168,8 @@ public class FormatTest { **/ @JsonProperty("float") @ApiModelProperty(value = "") - @DecimalMin("54.3") - @DecimalMax("987.6") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -191,8 +191,8 @@ public class FormatTest { **/ @JsonProperty("double") @ApiModelProperty(value = "") - @DecimalMin("67.8") - @DecimalMax("123.4") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -212,7 +212,7 @@ public class FormatTest { **/ @JsonProperty("string") @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -232,7 +232,7 @@ public class FormatTest { **/ @JsonProperty("byte") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public byte[] getByte() { return _byte; } @@ -271,7 +271,7 @@ public class FormatTest { **/ @JsonProperty("date") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public Date getDate() { return date; } @@ -329,8 +329,8 @@ public class FormatTest { **/ @JsonProperty("password") @ApiModelProperty(required = true, value = "") - @NotNull - @Size(min=10,max=64) + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java index 7d2c29e4430..c48051e1b8e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java @@ -49,7 +49,7 @@ public class Name { **/ @JsonProperty("name") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public Integer getName() { return name; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index 3070763de29..2b1c91b3d02 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -130,7 +130,7 @@ public class Pet { **/ @JsonProperty("name") @ApiModelProperty(example = "doggie", required = true, value = "") - @NotNull + @NotNull public String getName() { return name; } @@ -155,7 +155,7 @@ public class Pet { **/ @JsonProperty("photoUrls") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index 9b37ce040ba..1ef64321d6a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -1,43 +1,43 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class FakeApiServiceImpl extends FakeApiService { - @Override - public Response testClientModel(Client body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 689b00c86b2..4ca20a47727 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,73 +1,73 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class PetApiServiceImpl extends PetApiService { - @Override - public Response addPet(Pet body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getPetById(Long petId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePet(Pet body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class PetApiServiceImpl extends PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 28d031a4cb2..a1b85ef5f44 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,48 +1,48 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class StoreApiServiceImpl extends StoreApiService { - @Override - public Response deleteOrder( @Min(1.0)String orderId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getInventory(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response placeOrder(Order body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class StoreApiServiceImpl extends StoreApiService { + @Override + public Response deleteOrder( @Min(1.0)String orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 6ac7fec7fba..ca562ed389c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,72 +1,72 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import com.sun.jersey.multipart.FormDataParam; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import com.sun.jersey.core.header.FormDataContentDisposition; -import com.sun.jersey.multipart.FormDataParam; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class UserApiServiceImpl extends UserApiService { - @Override - public Response createUser(User body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deleteUser(String username, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getUserByName(String username, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response logoutUser(SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updateUser(String username, User body, SecurityContext securityContext) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import com.sun.jersey.multipart.FormDataParam; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class UserApiServiceImpl extends UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} From 157fcbc4aaec282ee4c7d24763e0b4a1b5d2814e Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 19 Jan 2017 16:54:16 +0800 Subject: [PATCH 266/269] fix invalid spec, update petstore samples (jaxrs, ruby) --- .../io/swagger/codegen/DefaultCodegen.java | 2 +- ...ith-fake-endpoints-models-for-testing.yaml | 1 - .../src/test/resources/2_0/petstore.yaml | 1 - samples/client/petstore/ruby/README.md | 1 + .../petstore/ruby/docs/Capitalization.md | 13 + samples/client/petstore/ruby/lib/petstore.rb | 1 + .../ruby/lib/petstore/api/fake_api.rb | 16 +- .../ruby/lib/petstore/api/store_api.rb | 12 +- .../lib/petstore/models/capitalization.rb | 233 ++++++++++++++++++ .../ruby/spec/models/capitalization_spec.rb | 71 ++++++ .../java/io/swagger/api/StoreApiService.java | 2 +- .../swagger/api/impl/StoreApiServiceImpl.java | 2 +- .../java/io/swagger/api/FakeApiService.java | 50 ++-- .../java/io/swagger/api/PetApiService.java | 60 ++--- .../java/io/swagger/api/StoreApiService.java | 50 ++-- .../java/io/swagger/api/UserApiService.java | 58 ++--- .../src/gen/java/io/swagger/model/Animal.java | 2 +- .../gen/java/io/swagger/model/FormatTest.java | 32 +-- .../src/gen/java/io/swagger/model/Name.java | 2 +- .../src/gen/java/io/swagger/model/Pet.java | 4 +- .../swagger/api/impl/FakeApiServiceImpl.java | 74 +++--- .../swagger/api/impl/PetApiServiceImpl.java | 124 +++++----- .../swagger/api/impl/StoreApiServiceImpl.java | 82 +++--- .../swagger/api/impl/UserApiServiceImpl.java | 122 ++++----- 24 files changed, 664 insertions(+), 351 deletions(-) create mode 100644 samples/client/petstore/ruby/docs/Capitalization.md create mode 100644 samples/client/petstore/ruby/lib/petstore/models/capitalization.rb create mode 100644 samples/client/petstore/ruby/spec/models/capitalization_spec.rb diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index b37e2860707..86a29382fdc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -2385,7 +2385,7 @@ public class DefaultCodegen { // validation // handle maximum, minimum properly for int/long by removing the trailing ".0" - if ("integer".equals(type)) { + if ("integer".equals(qp.getType())) { p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue()); p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue()); } else { diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 552dd2ee0ee..bb0e7e23370 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -367,7 +367,6 @@ paths: description: ID of the order that needs to be deleted required: true type: string - minimum: 1 responses: '400': description: Invalid ID supplied diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml index cd10223ba04..e3ba184ea57 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml @@ -367,7 +367,6 @@ paths: description: ID of the order that needs to be deleted required: true type: string - minimum: 1 responses: '400': description: Invalid ID supplied diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 2789989c589..83eb4707284 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -109,6 +109,7 @@ Class | Method | HTTP request | Description - [Petstore::ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [Petstore::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [Petstore::ArrayTest](docs/ArrayTest.md) + - [Petstore::Capitalization](docs/Capitalization.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/ruby/docs/Capitalization.md b/samples/client/petstore/ruby/docs/Capitalization.md new file mode 100644 index 00000000000..d99c603f54a --- /dev/null +++ b/samples/client/petstore/ruby/docs/Capitalization.md @@ -0,0 +1,13 @@ +# Petstore::Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **String** | | [optional] +**capital_camel** | **String** | | [optional] +**small_snake** | **String** | | [optional] +**capital_snake** | **String** | | [optional] +**sca_eth_flow_points** | **String** | | [optional] +**att_name** | **String** | Name of the pet | [optional] + + diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 6999fac514b..5644d820a27 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -23,6 +23,7 @@ require 'petstore/models/api_response' require 'petstore/models/array_of_array_of_number_only' require 'petstore/models/array_of_number_only' require 'petstore/models/array_test' +require 'petstore/models/capitalization' require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/class_model' diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 403705d2746..481004db585 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -145,20 +145,20 @@ module Petstore # verify the required parameter 'byte' is set fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" if byte.nil? - if !opts[:'integer'].nil? && opts[:'integer'] > 100 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.' + if !opts[:'integer'].nil? && opts[:'integer'] > 100.0 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.0.' end - if !opts[:'integer'].nil? && opts[:'integer'] < 10 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.' + if !opts[:'integer'].nil? && opts[:'integer'] < 10.0 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.0.' end - if !opts[:'int32'].nil? && opts[:'int32'] > 200 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.' + if !opts[:'int32'].nil? && opts[:'int32'] > 200.0 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.0.' end - if !opts[:'int32'].nil? && opts[:'int32'] < 20 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.' + if !opts[:'int32'].nil? && opts[:'int32'] < 20.0 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.0.' end if !opts[:'float'].nil? && opts[:'float'] > 987.6 diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 78755496444..39d5490b787 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -40,10 +40,6 @@ module Petstore end # verify the required parameter 'order_id' is set fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.delete_order" if order_id.nil? - if order_id < 1.0 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.delete_order, must be greater than or equal to 1.0.' - end - # resource path local_var_path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) @@ -141,12 +137,12 @@ module Petstore end # verify the required parameter 'order_id' is set fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.get_order_by_id" if order_id.nil? - if order_id > 5 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.' + if order_id > 5.0 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.0.' end - if order_id < 1 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.' + if order_id < 1.0 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.0.' end # resource path diff --git a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb new file mode 100644 index 00000000000..9dfd19523ea --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb @@ -0,0 +1,233 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'date' + +module Petstore + + class Capitalization + attr_accessor :small_camel + + attr_accessor :capital_camel + + attr_accessor :small_snake + + attr_accessor :capital_snake + + attr_accessor :sca_eth_flow_points + + # Name of the pet + attr_accessor :att_name + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'small_camel' => :'smallCamel', + :'capital_camel' => :'CapitalCamel', + :'small_snake' => :'small_Snake', + :'capital_snake' => :'Capital_Snake', + :'sca_eth_flow_points' => :'SCA_ETH_Flow_Points', + :'att_name' => :'ATT_NAME' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'small_camel' => :'String', + :'capital_camel' => :'String', + :'small_snake' => :'String', + :'capital_snake' => :'String', + :'sca_eth_flow_points' => :'String', + :'att_name' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'smallCamel') + self.small_camel = attributes[:'smallCamel'] + end + + if attributes.has_key?(:'CapitalCamel') + self.capital_camel = attributes[:'CapitalCamel'] + end + + if attributes.has_key?(:'small_Snake') + self.small_snake = attributes[:'small_Snake'] + end + + if attributes.has_key?(:'Capital_Snake') + self.capital_snake = attributes[:'Capital_Snake'] + end + + if attributes.has_key?(:'SCA_ETH_Flow_Points') + self.sca_eth_flow_points = attributes[:'SCA_ETH_Flow_Points'] + end + + if attributes.has_key?(:'ATT_NAME') + self.att_name = attributes[:'ATT_NAME'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + small_camel == o.small_camel && + capital_camel == o.capital_camel && + small_snake == o.small_snake && + capital_snake == o.capital_snake && + sca_eth_flow_points == o.sca_eth_flow_points && + att_name == o.att_name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [small_camel, capital_camel, small_snake, capital_snake, sca_eth_flow_points, att_name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/spec/models/capitalization_spec.rb b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb new file mode 100644 index 00000000000..372405eb7cd --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb @@ -0,0 +1,71 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Capitalization +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Capitalization' do + before do + # run before each test + @instance = Petstore::Capitalization.new + end + + after do + # run after each test + end + + describe 'test an instance of Capitalization' do + it 'should create an instact of Capitalization' do + expect(@instance).to be_instance_of(Petstore::Capitalization) + end + end + describe 'test attribute "small_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "small_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "sca_eth_flow_points"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "att_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java index 283e2687eb2..b5a01e43f3b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java @@ -21,7 +21,7 @@ import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; public abstract class StoreApiService { - public abstract Response deleteOrder( @Min(1.0)String orderId,SecurityContext securityContext) + public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index a1b85ef5f44..96194fb16b8 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -22,7 +22,7 @@ import javax.validation.constraints.*; public class StoreApiServiceImpl extends StoreApiService { @Override - public Response deleteOrder( @Min(1.0)String orderId, SecurityContext securityContext) + public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java index e49ec4c2d1c..aaff35dbdd9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java @@ -1,25 +1,25 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class FakeApiService { - public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class FakeApiService { + public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index 8ac5692e507..31566759c5f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -1,30 +1,30 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class PetApiService { - public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) throws NotFoundException; - public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; - public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; - public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class PetApiService { + public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) throws NotFoundException; + public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; + public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; + public abstract Response uploadFile(Long petId,String additionalMetadata,InputStream fileInputStream, FormDataContentDisposition fileDetail,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java index e472fd96f8f..911c70033c4 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -1,25 +1,25 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class StoreApiService { - public abstract Response deleteOrder( @Min(1.0)String orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) throws NotFoundException; - public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class StoreApiService { + public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java index 254895ec80b..8bbee3394d5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -1,29 +1,29 @@ -package io.swagger.api; - -import io.swagger.api.*; -import io.swagger.model.*; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public abstract class UserApiService { - public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; - public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; - public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; -} +package io.swagger.api; + +import io.swagger.api.*; +import io.swagger.model.*; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public abstract class UserApiService { + public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; + public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; + public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java index ff2a4f034eb..1898c8254e0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -44,7 +44,7 @@ public class Animal { **/ @JsonProperty("className") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public String getClassName() { return className; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index a2a748a08d7..973afef18fe 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -79,8 +79,8 @@ public class FormatTest { **/ @JsonProperty("integer") @ApiModelProperty(value = "") - @Min(10) - @Max(100) + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -102,8 +102,8 @@ public class FormatTest { **/ @JsonProperty("int32") @ApiModelProperty(value = "") - @Min(20) - @Max(200) + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -144,9 +144,9 @@ public class FormatTest { **/ @JsonProperty("number") @ApiModelProperty(required = true, value = "") - @NotNull - @DecimalMin("32.1") - @DecimalMax("543.2") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -168,8 +168,8 @@ public class FormatTest { **/ @JsonProperty("float") @ApiModelProperty(value = "") - @DecimalMin("54.3") - @DecimalMax("987.6") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -191,8 +191,8 @@ public class FormatTest { **/ @JsonProperty("double") @ApiModelProperty(value = "") - @DecimalMin("67.8") - @DecimalMax("123.4") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -212,7 +212,7 @@ public class FormatTest { **/ @JsonProperty("string") @ApiModelProperty(value = "") - @Pattern(regexp="/[a-z]/i") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -232,7 +232,7 @@ public class FormatTest { **/ @JsonProperty("byte") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public byte[] getByte() { return _byte; } @@ -271,7 +271,7 @@ public class FormatTest { **/ @JsonProperty("date") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public Date getDate() { return date; } @@ -329,8 +329,8 @@ public class FormatTest { **/ @JsonProperty("password") @ApiModelProperty(required = true, value = "") - @NotNull - @Size(min=10,max=64) + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java index 7d2c29e4430..c48051e1b8e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -49,7 +49,7 @@ public class Name { **/ @JsonProperty("name") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public Integer getName() { return name; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index 3070763de29..2b1c91b3d02 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -130,7 +130,7 @@ public class Pet { **/ @JsonProperty("name") @ApiModelProperty(example = "doggie", required = true, value = "") - @NotNull + @NotNull public String getName() { return name; } @@ -155,7 +155,7 @@ public class Pet { **/ @JsonProperty("photoUrls") @ApiModelProperty(required = true, value = "") - @NotNull + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index 98b6ea986c6..11b046e7c94 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -1,37 +1,37 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.math.BigDecimal; -import io.swagger.model.Client; -import java.util.Date; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class FakeApiServiceImpl extends FakeApiService { - @Override - public Response testClientModel(Client body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.util.Date; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class FakeApiServiceImpl extends FakeApiService { + @Override + public Response testClientModel(Client body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, Date date, Date dateTime, String password, String paramCallback, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 84b2d2d6b03..be3e7e167e7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -1,62 +1,62 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.io.File; -import io.swagger.model.ModelApiResponse; -import io.swagger.model.Pet; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class PetApiServiceImpl extends PetApiService { - @Override - public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class PetApiServiceImpl extends PetApiService { + @Override + public Response addPet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deletePet(Long petId, String apiKey, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getPetById(Long petId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePet(Pet body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updatePetWithForm(Long petId, String name, String status, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response uploadFile(Long petId, String additionalMetadata, InputStream fileInputStream, FormDataContentDisposition fileDetail, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index cddb935997d..f8fd4cec86b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -1,41 +1,41 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.util.Map; -import io.swagger.model.Order; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class StoreApiServiceImpl extends StoreApiService { - @Override - public Response deleteOrder( @Min(1.0)String orderId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getInventory(SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class StoreApiServiceImpl extends StoreApiService { + @Override + public Response deleteOrder(String orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getInventory(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response placeOrder(Order body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 6868d0a6105..5853e33168d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -1,61 +1,61 @@ -package io.swagger.api.impl; - -import io.swagger.api.*; -import io.swagger.model.*; - -import java.util.List; -import io.swagger.model.User; - -import java.util.List; -import io.swagger.api.NotFoundException; - -import java.io.InputStream; - -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; - -import javax.ws.rs.core.Response; -import javax.ws.rs.core.SecurityContext; -import javax.validation.constraints.*; - -public class UserApiServiceImpl extends UserApiService { - @Override - public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response logoutUser(SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - @Override - public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } -} +package io.swagger.api.impl; + +import io.swagger.api.*; +import io.swagger.model.*; + +import java.util.List; +import io.swagger.model.User; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; + +import javax.ws.rs.core.Response; +import javax.ws.rs.core.SecurityContext; +import javax.validation.constraints.*; + +public class UserApiServiceImpl extends UserApiService { + @Override + public Response createUser(User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response deleteUser(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response getUserByName(String username, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response logoutUser(SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override + public Response updateUser(String username, User body, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } +} From 6f4e82dc03ef1ab16dfe433ebfadfa917776f1a8 Mon Sep 17 00:00:00 2001 From: jfiala Date: Thu, 19 Jan 2017 10:45:17 +0100 Subject: [PATCH 267/269] [Jaxrs-Resteasy] Add beanvalidation annotations (#4506) * add beanvalidation to jaxrs-resteasy #4091 * replace tabs --- .../languages/JavaResteasyServerCodegen.java | 19 ++++++- .../resources/JavaJaxRS/resteasy/api.mustache | 3 ++ .../resteasy/beanValidation.mustache | 53 +++++++++++++++++++ .../beanValidationPathParams.mustache | 1 + .../beanValidationQueryParams.mustache | 1 + .../JavaJaxRS/resteasy/model.mustache | 4 +- .../JavaJaxRS/resteasy/pathParams.mustache | 2 +- .../JavaJaxRS/resteasy/pojo.mustache | 2 +- .../resources/JavaJaxRS/resteasy/pom.mustache | 10 ++++ .../JavaJaxRS/resteasy/queryParams.mustache | 2 +- .../jaxrs/JavaResteasyServerOptionsTest.java | 2 + .../JavaResteasyServerOptionsProvider.java | 4 ++ .../src/gen/java/io/swagger/api/PetApi.java | 5 +- .../src/gen/java/io/swagger/api/StoreApi.java | 5 +- .../src/gen/java/io/swagger/api/UserApi.java | 3 +- .../gen/java/io/swagger/model/Category.java | 2 +- .../io/swagger/model/ModelApiResponse.java | 2 +- .../src/gen/java/io/swagger/model/Order.java | 2 +- .../src/gen/java/io/swagger/model/Pet.java | 4 +- .../src/gen/java/io/swagger/model/Tag.java | 2 +- .../src/gen/java/io/swagger/model/User.java | 2 +- 21 files changed, 113 insertions(+), 17 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index c1bd8a23cd5..dffa0cffa36 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.codegen.languages.features.JbossFeature; import io.swagger.models.Operation; import org.apache.commons.lang3.BooleanUtils; @@ -9,10 +10,11 @@ import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.*; -public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature { +public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature, BeanValidationFeatures { + protected boolean useBeanValidation = true; protected boolean generateJbossDeploymentDescriptor = true; - + public JavaResteasyServerCodegen() { super(); @@ -35,6 +37,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im embeddedTemplateDir = templateDir = "JavaJaxRS" + File.separator + "resteasy"; + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); cliOptions.add( CliOption.newBoolean(GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, "Generate Jboss Deployment Descriptor")); } @@ -58,6 +61,14 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); @@ -214,6 +225,10 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im return objs; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache index 6354f755b8b..e6353b36a0c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache @@ -16,6 +16,9 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#operations}}{{#operation}}{{#isMultipart}}import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; {{/isMultipart}}{{/operation}}{{/operations}} @Path("/{{baseName}}") diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache index 916d909c546..2ff294581f5 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache @@ -7,7 +7,9 @@ import java.util.ArrayList; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache index 39116c805cb..0cd6809df54 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}} @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}} @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache index b51330b49c6..aba53ed6666 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache @@ -15,7 +15,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali **/ {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @JsonProperty("{{baseName}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache index 6c4c547d5c1..c5699ecf00c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -138,6 +138,16 @@ +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache index 458b8de7c3b..5a9a4398a03 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java index 8d74b035901..d76ee89416f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java @@ -59,6 +59,8 @@ public class JavaResteasyServerOptionsTest extends AbstractOptionsTest { clientCodegen.setGenerateJbossDeploymentDescriptor( Boolean.valueOf(JavaResteasyServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); + + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaResteasyServerOptionsProvider.USE_BEANVALIDATION)); times = 1; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java index 769f759d95c..eae8a6dcccf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java @@ -6,6 +6,7 @@ import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaCXFServerCodegen; +import io.swagger.codegen.languages.JavaResteasyServerCodegen; public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { @@ -13,6 +14,8 @@ public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { public static final String IMPL_FOLDER_VALUE = "src/main/java"; + public static final String USE_BEANVALIDATION = "true"; + @Override public boolean isServer() { return true; @@ -35,6 +38,7 @@ public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { builder.put("title", "Test title"); builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + builder.put(JavaResteasyServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); return builder.build(); diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java index c969d1e0b8c..ccefa906b05 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; @Path("/pet") @@ -46,7 +47,7 @@ public class PetApi { @Path("/findByStatus") @Produces({ "application/xml", "application/json" }) - public Response findPetsByStatus( @QueryParam("status") List status,@Context SecurityContext securityContext) + public Response findPetsByStatus( @NotNull @QueryParam("status") List status,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); } @@ -54,7 +55,7 @@ public class PetApi { @Path("/findByTags") @Produces({ "application/xml", "application/json" }) - public Response findPetsByTags( @QueryParam("tags") List tags,@Context SecurityContext securityContext) + public Response findPetsByTags( @NotNull @QueryParam("tags") List tags,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java index dcc585fabc2..d0d5bf43537 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/store") @@ -28,7 +29,7 @@ public class StoreApi { @Path("/order/{orderId}") @Produces({ "application/xml", "application/json" }) - public Response deleteOrder( @PathParam("orderId") String orderId,@Context SecurityContext securityContext) + public Response deleteOrder( @Min(1) @PathParam("orderId") String orderId,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deleteOrder(orderId,securityContext); } @@ -44,7 +45,7 @@ public class StoreApi { @Path("/order/{orderId}") @Produces({ "application/xml", "application/json" }) - public Response getOrderById( @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + public Response getOrderById( @Min(1) @Max(5) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java index d101d862f80..177cd17ebcc 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/user") @@ -68,7 +69,7 @@ public class UserApi { @Path("/login") @Produces({ "application/xml", "application/json" }) - public Response loginUser( @QueryParam("username") String username, @QueryParam("password") String password,@Context SecurityContext securityContext) + public Response loginUser( @NotNull @QueryParam("username") String username, @NotNull @QueryParam("password") String password,@Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java index a551df116fc..a6ad13bbf0e 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; public class Category { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java index c8898f86971..12188bbfd2c 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; public class ModelApiResponse { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java index 586d4b195b3..009b4b6aab4 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import java.util.Date; - +import javax.validation.constraints.*; public class Order { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java index 685d7ab6ee6..0ca31f939b8 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.List; - +import javax.validation.constraints.*; public class Pet { @@ -69,6 +69,7 @@ public class Pet { **/ @JsonProperty("name") + @NotNull public String getName() { return name; } @@ -80,6 +81,7 @@ public class Pet { **/ @JsonProperty("photoUrls") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java index 48a6ab94a85..06843880d11 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; public class Tag { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java index e95e76c1b41..53de0ce4c8c 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; public class User { From 36c3fa05e05f70d5164b34be06e6c240479dec53 Mon Sep 17 00:00:00 2001 From: Jonathan Leitschuh Date: Thu, 19 Jan 2017 04:58:39 -0500 Subject: [PATCH 268/269] Allows for generation of spring controller code using the delegate pattern (#4439) * Allows for generation of spring conroller code using the decorator pattern * Change Decorator to Delegate in spring codegen --- bin/spring-all-pestore.sh | 2 + bin/spring-delegate-j8.sh | 34 ++ bin/spring-delegate.sh | 34 ++ .../codegen/languages/SpringCodegen.java | 24 ++ .../JavaSpring/apiController.mustache | 25 +- .../resources/JavaSpring/apiDelegate.mustache | 37 ++ .../options/SpringOptionsProvider.java | 2 + .../codegen/spring/SpringOptionsTest.java | 2 + .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../src/main/java/io/swagger/api/UserApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../src/main/java/io/swagger/api/UserApi.java | 2 +- .../src/main/java/io/swagger/api/FakeApi.java | 12 +- .../io/swagger/api/FakeApiController.java | 2 + .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../java/io/swagger/api/PetApiController.java | 2 + .../io/swagger/api/StoreApiController.java | 2 + .../src/main/java/io/swagger/api/UserApi.java | 2 +- .../io/swagger/api/UserApiController.java | 2 + .../main/java/io/swagger/model/Animal.java | 2 + .../java/io/swagger/model/Capitalization.java | 189 +++++++++ .../java/io/swagger/model/ClassModel.java | 75 ++++ .../main/java/io/swagger/model/EnumTest.java | 28 +- .../java/io/swagger/model/FormatTest.java | 8 +- .../main/java/io/swagger/model/OuterEnum.java | 41 ++ .../src/main/java/io/swagger/api/FakeApi.java | 10 +- .../io/swagger/api/FakeApiController.java | 8 +- .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../java/io/swagger/api/PetApiController.java | 6 +- .../io/swagger/api/StoreApiController.java | 2 + .../src/main/java/io/swagger/api/UserApi.java | 2 +- .../io/swagger/api/UserApiController.java | 4 +- .../main/java/io/swagger/model/Animal.java | 2 + .../java/io/swagger/model/Capitalization.java | 189 +++++++++ .../java/io/swagger/model/ClassModel.java | 75 ++++ .../main/java/io/swagger/model/EnumTest.java | 28 +- .../java/io/swagger/model/FormatTest.java | 8 +- .../main/java/io/swagger/model/OuterEnum.java | 41 ++ .../.swagger-codegen-ignore | 23 ++ .../petstore/springboot-delegate-j8/README.md | 18 + .../petstore/springboot-delegate-j8/pom.xml | 62 +++ .../java/io/swagger/RFC3339DateFormat.java | 20 + .../java/io/swagger/Swagger2SpringBoot.java | 36 ++ .../java/io/swagger/api/ApiException.java | 10 + .../java/io/swagger/api/ApiOriginFilter.java | 27 ++ .../io/swagger/api/ApiResponseMessage.java | 69 ++++ .../src/main/java/io/swagger/api/FakeApi.java | 88 +++++ .../io/swagger/api/FakeApiController.java | 69 ++++ .../java/io/swagger/api/FakeApiDelegate.java | 67 ++++ .../io/swagger/api/NotFoundException.java | 10 + .../src/main/java/io/swagger/api/PetApi.java | 172 +++++++++ .../java/io/swagger/api/PetApiController.java | 78 ++++ .../java/io/swagger/api/PetApiDelegate.java | 91 +++++ .../main/java/io/swagger/api/StoreApi.java | 77 ++++ .../io/swagger/api/StoreApiController.java | 52 +++ .../java/io/swagger/api/StoreApiDelegate.java | 53 +++ .../src/main/java/io/swagger/api/UserApi.java | 126 ++++++ .../io/swagger/api/UserApiController.java | 74 ++++ .../java/io/swagger/api/UserApiDelegate.java | 87 +++++ .../swagger/configuration/HomeController.java | 16 + .../SwaggerDocumentationConfig.java | 40 ++ .../model/AdditionalPropertiesClass.java | 110 ++++++ .../main/java/io/swagger/model/Animal.java | 99 +++++ .../java/io/swagger/model/AnimalFarm.java | 50 +++ .../model/ArrayOfArrayOfNumberOnly.java | 82 ++++ .../io/swagger/model/ArrayOfNumberOnly.java | 82 ++++ .../main/java/io/swagger/model/ArrayTest.java | 138 +++++++ .../java/io/swagger/model/Capitalization.java | 189 +++++++++ .../src/main/java/io/swagger/model/Cat.java | 76 ++++ .../main/java/io/swagger/model/Category.java | 97 +++++ .../java/io/swagger/model/ClassModel.java | 75 ++++ .../main/java/io/swagger/model/Client.java | 74 ++++ .../src/main/java/io/swagger/model/Dog.java | 76 ++++ .../java/io/swagger/model/EnumArrays.java | 167 ++++++++ .../main/java/io/swagger/model/EnumClass.java | 41 ++ .../main/java/io/swagger/model/EnumTest.java | 240 ++++++++++++ .../java/io/swagger/model/FormatTest.java | 363 ++++++++++++++++++ .../io/swagger/model/HasOnlyReadOnly.java | 97 +++++ .../main/java/io/swagger/model/MapTest.java | 142 +++++++ ...ropertiesAndAdditionalPropertiesClass.java | 130 +++++++ .../io/swagger/model/Model200Response.java | 98 +++++ .../io/swagger/model/ModelApiResponse.java | 120 ++++++ .../java/io/swagger/model/ModelReturn.java | 75 ++++ .../src/main/java/io/swagger/model/Name.java | 144 +++++++ .../java/io/swagger/model/NumberOnly.java | 75 ++++ .../src/main/java/io/swagger/model/Order.java | 224 +++++++++++ .../main/java/io/swagger/model/OuterEnum.java | 41 ++ .../src/main/java/io/swagger/model/Pet.java | 237 ++++++++++++ .../java/io/swagger/model/ReadOnlyFirst.java | 97 +++++ .../io/swagger/model/SpecialModelName.java | 74 ++++ .../src/main/java/io/swagger/model/Tag.java | 97 +++++ .../src/main/java/io/swagger/model/User.java | 235 ++++++++++++ .../src/main/resources/application.properties | 5 + .../.swagger-codegen-ignore | 23 ++ .../petstore/springboot-delegate/README.md | 18 + .../petstore/springboot-delegate/pom.xml | 66 ++++ .../java/io/swagger/RFC3339DateFormat.java | 20 + .../java/io/swagger/Swagger2SpringBoot.java | 36 ++ .../java/io/swagger/api/ApiException.java | 10 + .../java/io/swagger/api/ApiOriginFilter.java | 27 ++ .../io/swagger/api/ApiResponseMessage.java | 69 ++++ .../src/main/java/io/swagger/api/FakeApi.java | 78 ++++ .../io/swagger/api/FakeApiController.java | 69 ++++ .../java/io/swagger/api/FakeApiDelegate.java | 57 +++ .../io/swagger/api/NotFoundException.java | 10 + .../src/main/java/io/swagger/api/PetApi.java | 147 +++++++ .../java/io/swagger/api/PetApiController.java | 78 ++++ .../java/io/swagger/api/PetApiDelegate.java | 66 ++++ .../main/java/io/swagger/api/StoreApi.java | 64 +++ .../io/swagger/api/StoreApiController.java | 52 +++ .../java/io/swagger/api/StoreApiDelegate.java | 40 ++ .../src/main/java/io/swagger/api/UserApi.java | 101 +++++ .../io/swagger/api/UserApiController.java | 74 ++++ .../java/io/swagger/api/UserApiDelegate.java | 62 +++ .../swagger/configuration/HomeController.java | 16 + .../SwaggerDocumentationConfig.java | 40 ++ .../model/AdditionalPropertiesClass.java | 110 ++++++ .../main/java/io/swagger/model/Animal.java | 99 +++++ .../java/io/swagger/model/AnimalFarm.java | 50 +++ .../model/ArrayOfArrayOfNumberOnly.java | 82 ++++ .../io/swagger/model/ArrayOfNumberOnly.java | 82 ++++ .../main/java/io/swagger/model/ArrayTest.java | 138 +++++++ .../java/io/swagger/model/Capitalization.java | 189 +++++++++ .../src/main/java/io/swagger/model/Cat.java | 76 ++++ .../main/java/io/swagger/model/Category.java | 97 +++++ .../java/io/swagger/model/ClassModel.java | 75 ++++ .../main/java/io/swagger/model/Client.java | 74 ++++ .../src/main/java/io/swagger/model/Dog.java | 76 ++++ .../java/io/swagger/model/EnumArrays.java | 167 ++++++++ .../main/java/io/swagger/model/EnumClass.java | 41 ++ .../main/java/io/swagger/model/EnumTest.java | 240 ++++++++++++ .../java/io/swagger/model/FormatTest.java | 363 ++++++++++++++++++ .../io/swagger/model/HasOnlyReadOnly.java | 97 +++++ .../main/java/io/swagger/model/MapTest.java | 142 +++++++ ...ropertiesAndAdditionalPropertiesClass.java | 130 +++++++ .../io/swagger/model/Model200Response.java | 98 +++++ .../io/swagger/model/ModelApiResponse.java | 120 ++++++ .../java/io/swagger/model/ModelReturn.java | 75 ++++ .../src/main/java/io/swagger/model/Name.java | 144 +++++++ .../java/io/swagger/model/NumberOnly.java | 75 ++++ .../src/main/java/io/swagger/model/Order.java | 224 +++++++++++ .../main/java/io/swagger/model/OuterEnum.java | 41 ++ .../src/main/java/io/swagger/model/Pet.java | 237 ++++++++++++ .../java/io/swagger/model/ReadOnlyFirst.java | 97 +++++ .../io/swagger/model/SpecialModelName.java | 74 ++++ .../src/main/java/io/swagger/model/Tag.java | 97 +++++ .../src/main/java/io/swagger/model/User.java | 235 ++++++++++++ .../src/main/resources/application.properties | 5 + .../src/main/java/io/swagger/api/FakeApi.java | 10 +- .../io/swagger/api/FakeApiController.java | 8 +- .../src/main/java/io/swagger/api/PetApi.java | 4 +- .../java/io/swagger/api/PetApiController.java | 6 +- .../io/swagger/api/StoreApiController.java | 2 + .../src/main/java/io/swagger/api/UserApi.java | 2 +- .../io/swagger/api/UserApiController.java | 4 +- .../main/java/io/swagger/model/Animal.java | 2 + .../java/io/swagger/model/Capitalization.java | 189 +++++++++ .../java/io/swagger/model/ClassModel.java | 75 ++++ .../main/java/io/swagger/model/EnumTest.java | 28 +- .../java/io/swagger/model/FormatTest.java | 8 +- .../main/java/io/swagger/model/OuterEnum.java | 41 ++ 161 files changed, 11518 insertions(+), 69 deletions(-) create mode 100755 bin/spring-delegate-j8.sh create mode 100755 bin/spring-delegate.sh create mode 100644 modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache create mode 100644 samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java create mode 100644 samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java create mode 100644 samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore create mode 100644 samples/server/petstore/springboot-delegate-j8/README.md create mode 100644 samples/server/petstore/springboot-delegate-j8/pom.xml create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java create mode 100644 samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties create mode 100644 samples/server/petstore/springboot-delegate/.swagger-codegen-ignore create mode 100644 samples/server/petstore/springboot-delegate/README.md create mode 100644 samples/server/petstore/springboot-delegate/pom.xml create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java create mode 100644 samples/server/petstore/springboot-delegate/src/main/resources/application.properties create mode 100644 samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java create mode 100644 samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java create mode 100644 samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java diff --git a/bin/spring-all-pestore.sh b/bin/spring-all-pestore.sh index de3998266f0..eb69ef2c4ac 100755 --- a/bin/spring-all-pestore.sh +++ b/bin/spring-all-pestore.sh @@ -1,6 +1,8 @@ #!/bin/sh ./bin/spring-cloud-feign-petstore.sh +./bin/spring-delegate.sh +./bin/spring-delegate-j8.sh ./bin/spring-stubs.sh ./bin/spring-mvc-petstore-j8-async-server.sh ./bin/springboot-petstore-server.sh diff --git a/bin/spring-delegate-j8.sh b/bin/spring-delegate-j8.sh new file mode 100755 index 00000000000..1edb371ba49 --- /dev/null +++ b/bin/spring-delegate-j8.sh @@ -0,0 +1,34 @@ +#!/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 -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot-delegate-j8 -DdelegatePattern=true,hideGenerationTimestamp=true,java8=true" + +echo "Removing files and folders under samples/server/petstore/springboot-delegate-j8/src/main" +rm -rf samples/server/petstore/springboot/src/main +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-delegate.sh b/bin/spring-delegate.sh new file mode 100755 index 00000000000..f63e617556c --- /dev/null +++ b/bin/spring-delegate.sh @@ -0,0 +1,34 @@ +#!/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 -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot-delegate -DdelegatePattern=true,hideGenerationTimestamp=true" + +echo "Removing files and folders under samples/server/petstore/springboot-delegate/src/main" +rm -rf samples/server/petstore/springboot/src/main +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index cf2ff55e7c5..1ef8bf51984 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -14,6 +14,7 @@ public class SpringCodegen extends AbstractJavaCodegen { public static final String CONFIG_PACKAGE = "configPackage"; public static final String BASE_PACKAGE = "basePackage"; public static final String INTERFACE_ONLY = "interfaceOnly"; + public static final String DELEGATE_PATTERN = "delegatePattern"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String JAVA_8 = "java8"; public static final String ASYNC = "async"; @@ -26,6 +27,7 @@ public class SpringCodegen extends AbstractJavaCodegen { protected String configPackage = "io.swagger.configuration"; protected String basePackage = "io.swagger"; protected boolean interfaceOnly = false; + protected boolean delegatePattern = false; protected boolean singleContentTypes = false; protected boolean java8 = false; protected boolean async = false; @@ -52,6 +54,7 @@ public class SpringCodegen extends AbstractJavaCodegen { cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern")); cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); @@ -111,6 +114,10 @@ public class SpringCodegen extends AbstractJavaCodegen { this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); } + if (additionalProperties.containsKey(DELEGATE_PATTERN)) { + this.setDelegatePattern(Boolean.valueOf(additionalProperties.get(DELEGATE_PATTERN).toString())); + } + if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); } @@ -134,6 +141,11 @@ public class SpringCodegen extends AbstractJavaCodegen { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + if (this.interfaceOnly && this.delegatePattern) { + throw new IllegalArgumentException( + String.format("Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, INTERFACE_ONLY)); + } + if (!this.interfaceOnly) { if (library.equals(DEFAULT_LIBRARY)) { supportingFiles.add(new SupportingFile("homeController.mustache", @@ -184,6 +196,16 @@ public class SpringCodegen extends AbstractJavaCodegen { } } + if (!this.delegatePattern && this.java8) { + additionalProperties.put("jdk8-no-delegate", true); + } + + + if (this.delegatePattern) { + additionalProperties.put("isDelegate", "true"); + apiTemplateFiles.put("apiDelegate.mustache", "Delegate.java"); + } + if (this.java8) { additionalProperties.put("javaVersion", "1.8"); additionalProperties.put("jdk8", "true"); @@ -397,6 +419,8 @@ public class SpringCodegen extends AbstractJavaCodegen { public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } + public void setDelegatePattern(boolean delegatePattern) { this.delegatePattern = delegatePattern; } + public void setSingleContentTypes(boolean singleContentTypes) { this.singleContentTypes = singleContentTypes; } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache index 456176a05c2..94356ac2d20 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache @@ -1,6 +1,6 @@ package {{package}}; -{{^jdk8}} +{{^jdk8-no-delegate}} {{#imports}}import {{import}}; {{/imports}} @@ -8,9 +8,9 @@ import io.swagger.annotations.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -{{/jdk8}} +{{/jdk8-no-delegate}} import org.springframework.stereotype.Controller; -{{^jdk8}} +{{^jdk8-no-delegate}} import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,24 +21,33 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; {{#async}} import java.util.concurrent.Callable; -{{/async}}{{/jdk8}} +{{/async}}{{/jdk8-no-delegate}} {{>generatedAnnotation}} @Controller {{#operations}} public class {{classname}}Controller implements {{classname}} { -{{^jdk8}}{{#operation}} +{{#isDelegate}} + private final {{classname}}Delegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + {{classname}}Controller({{classname}}Delegate delegate) { + this.delegate = delegate; + }{{/isDelegate}} + +{{^jdk8-no-delegate}}{{#operation}} public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // do some magic!{{^async}} + // do some magic!{{^isDelegate}}{{^async}} return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}} return new CallablereturnTypes}}>>() { @Override public ResponseEntity<{{>returnTypes}}> call() throws Exception { return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); } - };{{/async}} + };{{/async}}{{/isDelegate}}{{#isDelegate}} + return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/isDelegate}} } -{{/operation}}{{/jdk8}} +{{/operation}}{{/jdk8-no-delegate}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache new file mode 100644 index 00000000000..eed583ea916 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache @@ -0,0 +1,37 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*;{{#jdk8}} +import org.springframework.http.HttpStatus;{{/jdk8}} +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +{{#async}} +import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}}; +{{/async}} + +{{#operations}} +/** + * A delegate to be called by the {@link {{classname}}Controller}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link {{classname}}Controller}. + */ +{{>generatedAnnotation}} +public interface {{classname}}Delegate { + +{{#operation}} + /** + * @see {{classname}}#{{operationId}} + */ + {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}}{{{dataType}}}{{/isFile}}{{#isFile}}MultipartFile{{/isFile}} {{paramName}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} { + // do some magic! + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}}; + }{{/jdk8}} + +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index 55ef56bf505..bfb598f49b0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -12,6 +12,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { public static final String BASE_PACKAGE_VALUE = "basePackage"; public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class public static final String INTERFACE_ONLY = "true"; + public static final String DELEGATE_PATTERN = "true"; public static final String SINGLE_CONTENT_TYPES = "true"; public static final String JAVA_8 = "true"; public static final String ASYNC = "true"; @@ -31,6 +32,7 @@ public class SpringOptionsProvider extends JavaOptionsProvider { options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); + options.put(SpringCodegen.DELEGATE_PATTERN, DELEGATE_PATTERN); options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); options.put(SpringCodegen.JAVA_8, JAVA_8); options.put(SpringCodegen.ASYNC, ASYNC); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 65894ba558f..6a45f5f976d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -58,6 +58,8 @@ public class SpringOptionsTest extends JavaClientOptionsTest { times = 1; clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); times = 1; + clientCodegen.setDelegatePattern(Boolean.valueOf(SpringOptionsProvider.DELEGATE_PATTERN)); + times = 1; clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); times = 1; clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index fea0638305c..49a2c91817e 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java index 6c900273049..1ecef6bfecb 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java index 04c4ed27aa3..735c9548bcc 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java index 40bdddedbb8..e212a819908 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 0101645ad5f..0e6a9276c38 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -1,9 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; -import java.time.OffsetDateTime; -import java.time.LocalDate; import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; @@ -24,7 +24,7 @@ import java.util.concurrent.CompletableFuture; @Api(value = "fake", description = "the fake API") public interface FakeApi { - @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @RequestMapping(value = "/fake", @@ -66,7 +66,7 @@ public interface FakeApi { } - @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request", response = Void.class), @ApiResponse(code = 404, message = "Not found", response = Void.class) }) @@ -80,7 +80,7 @@ public interface FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java index 31729a28177..1c9b2129632 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java @@ -7,4 +7,6 @@ import org.springframework.stereotype.Controller; @Controller public class FakeApiController implements FakeApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index 6a8018d2c21..3727f1898c7 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java index 68d93c1b173..158ab5bae23 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java @@ -7,4 +7,6 @@ import org.springframework.stereotype.Controller; @Controller public class PetApiController implements PetApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java index 470516e48f0..a0afb7c9b74 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java @@ -7,4 +7,6 @@ import org.springframework.stereotype.Controller; @Controller public class StoreApiController implements StoreApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index 05e52b041f3..919e67d2cab 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; import org.springframework.http.HttpStatus; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java index 7ecb3ed8e0b..fa09b8491d6 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java @@ -7,4 +7,6 @@ import org.springframework.stereotype.Controller; @Controller public class UserApiController implements UserApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java index de739ed501c..60aaf82231f 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java @@ -3,6 +3,8 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..94cb9977104 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..16c743e4f32 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java index dc00d569c7e..d081e726855 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; /** * EnumTest @@ -116,6 +117,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -170,6 +174,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -182,12 +204,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @Override @@ -198,6 +221,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java index 242a20cfc3b..74cf9dda458 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java @@ -60,8 +60,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(value = "") @@ -80,8 +80,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(value = "") diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..0abc3d063b5 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index 6fb7235d18b..7a9f9fc2920 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -1,9 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; -import org.joda.time.LocalDate; import java.math.BigDecimal; +import io.swagger.model.Client; import org.joda.time.DateTime; +import org.joda.time.LocalDate; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -22,7 +22,7 @@ import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { - @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @RequestMapping(value = "/fake", @@ -58,7 +58,7 @@ public interface FakeApi { @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback); - @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request", response = Void.class), @ApiResponse(code = 404, message = "Not found", response = Void.class) }) @@ -72,7 +72,7 @@ public interface FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index f4adae4ec88..0e2279b664e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -1,9 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; -import org.joda.time.LocalDate; import java.math.BigDecimal; +import io.swagger.model.Client; import org.joda.time.DateTime; +import org.joda.time.LocalDate; import io.swagger.annotations.*; @@ -24,6 +24,8 @@ import java.util.List; @Controller public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -53,7 +55,7 @@ public class FakeApiController implements FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 5b69114555e..7d48cfb31c9 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index 695d4cc2386..ee499f0d27f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; @@ -23,6 +23,8 @@ import java.util.List; @Controller public class PetApiController implements PetApi { + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java index bd582ae1a94..2cc8b49c41e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java @@ -22,6 +22,8 @@ import java.util.List; @Controller public class StoreApiController implements StoreApi { + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 44a359c309d..c31b5a143ee 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java index a5a6d4d4505..81d3dabb762 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; @@ -22,6 +22,8 @@ import java.util.List; @Controller public class UserApiController implements UserApi { + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java index de739ed501c..60aaf82231f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java @@ -3,6 +3,8 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..94cb9977104 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..16c743e4f32 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java index dc00d569c7e..d081e726855 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; /** * EnumTest @@ -116,6 +117,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -170,6 +174,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -182,12 +204,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @Override @@ -198,6 +221,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java index 8d3cd2bec93..6367fe81b0c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java @@ -60,8 +60,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(value = "") @@ -80,8 +80,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(value = "") diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..0abc3d063b5 --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore b/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/springboot-delegate-j8/README.md b/samples/server/petstore/springboot-delegate-j8/README.md new file mode 100644 index 00000000000..a2e8a9f7b84 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/README.md @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/pom.xml b/samples/server/petstore/springboot-delegate-j8/pom.xml new file mode 100644 index 00000000000..fba801c6b4e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/pom.xml @@ -0,0 +1,62 @@ + + 4.0.0 + io.swagger + swagger-spring + jar + swagger-spring + 1.0.0 + + 1.8 + ${java.version} + ${java.version} + 2.5.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java new file mode 100644 index 00000000000..c06fbae3c7a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -0,0 +1,36 @@ +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..7fa61c50d24 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..f0f62dc7206 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..f03840f8e06 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..517676dd81a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,88 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + method = RequestMethod.POST) + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "*/*" }, + consumes = { "*/*" }, + method = RequestMethod.GET) + default ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java new file mode 100644 index 00000000000..1f50d06a2f3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class FakeApiController implements FakeApi { + private final FakeApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + FakeApiController(FakeApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return delegate.testClientModel(body); + } + + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java new file mode 100644 index 00000000000..96d5e63a372 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -0,0 +1,67 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link FakeApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link FakeApiController}. + */ + +public interface FakeApiDelegate { + + /** + * @see FakeApi#testClientModel + */ + default ResponseEntity testClientModel(Client body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see FakeApi#testEndpointParameters + */ + default ResponseEntity testEndpointParameters(BigDecimal number, + Double _double, + String patternWithoutDelimiter, + byte[] _byte, + Integer integer, + Integer int32, + Long int64, + Float _float, + String string, + byte[] binary, + LocalDate date, + OffsetDateTime dateTime, + String password, + String paramCallback) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see FakeApi#testEnumParameters + */ + default ResponseEntity testEnumParameters(List enumFormStringArray, + String enumFormString, + List enumHeaderStringArray, + String enumHeaderString, + List enumQueryStringArray, + String enumQueryString, + Integer enumQueryInteger, + Double enumQueryDouble) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..295109d7fc4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..d1bd561ef8f --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,172 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.POST) + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.PUT) + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + consumes = { "application/x-www-form-urlencoded" }, + method = RequestMethod.POST) + default ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" }, + method = RequestMethod.POST) + default ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..6eb175b89f0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class PetApiController implements PetApi { + private final PetApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + PetApiController(PetApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.addPet(body); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return delegate.deletePet(petId, apiKey); + } + + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return delegate.findPetsByStatus(status); + } + + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return delegate.findPetsByTags(tags); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return delegate.getPetById(petId); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.updatePet(body); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return delegate.updatePetWithForm(petId, name, status); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return delegate.uploadFile(petId, additionalMetadata, file); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java new file mode 100644 index 00000000000..7f89dfdabb4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java @@ -0,0 +1,91 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link PetApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link PetApiController}. + */ + +public interface PetApiDelegate { + + /** + * @see PetApi#addPet + */ + default ResponseEntity addPet(Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#deletePet + */ + default ResponseEntity deletePet(Long petId, + String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#findPetsByStatus + */ + default ResponseEntity> findPetsByStatus(List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see PetApi#findPetsByTags + */ + default ResponseEntity> findPetsByTags(List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see PetApi#getPetById + */ + default ResponseEntity getPetById(Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#updatePet + */ + default ResponseEntity updatePet(Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#updatePetWithForm + */ + default ResponseEntity updatePetWithForm(Long petId, + String name, + String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#uploadFile + */ + default ResponseEntity uploadFile(Long petId, + String additionalMetadata, + MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..2827642886a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,77 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = { "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..6215ded3540 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,52 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class StoreApiController implements StoreApi { + private final StoreApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + StoreApiController(StoreApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return delegate.deleteOrder(orderId); + } + + public ResponseEntity> getInventory() { + // do some magic! + return delegate.getInventory(); + } + + public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return delegate.getOrderById(orderId); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return delegate.placeOrder(body); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java new file mode 100644 index 00000000000..17a4dfc2a9d --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -0,0 +1,53 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link StoreApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link StoreApiController}. + */ + +public interface StoreApiDelegate { + + /** + * @see StoreApi#deleteOrder + */ + default ResponseEntity deleteOrder(String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see StoreApi#getInventory + */ + default ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see StoreApi#getOrderById + */ + default ResponseEntity getOrderById(Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see StoreApi#placeOrder + */ + default ResponseEntity placeOrder(Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..bcc8700bed1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,126 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.PUT) + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..7cb74a3e172 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,74 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class UserApiController implements UserApi { + private final UserApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + UserApiController(UserApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.createUser(body); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithArrayInput(body); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithListInput(body); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.deleteUser(username); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.getUserByName(username); + } + + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return delegate.loginUser(username, password); + } + + public ResponseEntity logoutUser() { + // do some magic! + return delegate.logoutUser(); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.updateUser(username, body); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java new file mode 100644 index 00000000000..435efd58a8e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java @@ -0,0 +1,87 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link UserApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link UserApiController}. + */ + +public interface UserApiDelegate { + + /** + * @see UserApi#createUser + */ + default ResponseEntity createUser(User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#createUsersWithArrayInput + */ + default ResponseEntity createUsersWithArrayInput(List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#createUsersWithListInput + */ + default ResponseEntity createUsersWithListInput(List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#deleteUser + */ + default ResponseEntity deleteUser(String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#getUserByName + */ + default ResponseEntity getUserByName(String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#loginUser + */ + default ResponseEntity loginUser(String username, + String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#logoutUser + */ + default ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#updateUser + */ + default ResponseEntity updateUser(String username, + User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java new file mode 100644 index 00000000000..d195523c1d3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java @@ -0,0 +1,16 @@ +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java new file mode 100644 index 00000000000..962607f9340 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -0,0 +1,40 @@ +package io.swagger.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + +@Configuration +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Swagger Petstore") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("","", "apiteam@swagger.io")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) + .build() + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class) + .apiInfo(apiInfo()); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..60aaf82231f --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,99 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..94cb9977104 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..ba1ecfdb2b8 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..16c743e4f32 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..d081e726855 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,240 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..74cf9dda458 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,363 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..55817f8dd14 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..ea443a94338 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..82f447004ee --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,120 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..aa31ac8d79a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,144 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..cee3ae6d708 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,224 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..0abc3d063b5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..823d25e05a0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,237 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..76d529c087a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..846812a5031 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..52c5fff826e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java @@ -0,0 +1,235 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties b/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties new file mode 100644 index 00000000000..a2ef8627027 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties @@ -0,0 +1,5 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore b/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/springboot-delegate/README.md b/samples/server/petstore/springboot-delegate/README.md new file mode 100644 index 00000000000..a2e8a9f7b84 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/README.md @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/pom.xml b/samples/server/petstore/springboot-delegate/pom.xml new file mode 100644 index 00000000000..fdb0b535b34 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/pom.xml @@ -0,0 +1,66 @@ + + 4.0.0 + io.swagger + swagger-spring + jar + swagger-spring + 1.0.0 + + 1.7 + ${java.version} + ${java.version} + 2.5.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + + + joda-time + joda-time + + + \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java new file mode 100644 index 00000000000..c06fbae3c7a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -0,0 +1,36 @@ +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..7fa61c50d24 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..f0f62dc7206 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..f03840f8e06 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..7a9f9fc2920 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body); + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + method = RequestMethod.POST) + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) DateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback); + + + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "*/*" }, + consumes = { "*/*" }, + method = RequestMethod.GET) + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java new file mode 100644 index 00000000000..cee03f014a1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class FakeApiController implements FakeApi { + private final FakeApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + FakeApiController(FakeApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return delegate.testClientModel(body); + } + + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) DateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java new file mode 100644 index 00000000000..a7f2cc2dc91 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -0,0 +1,57 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link FakeApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link FakeApiController}. + */ + +public interface FakeApiDelegate { + + /** + * @see FakeApi#testClientModel + */ + ResponseEntity testClientModel(Client body); + + /** + * @see FakeApi#testEndpointParameters + */ + ResponseEntity testEndpointParameters(BigDecimal number, + Double _double, + String patternWithoutDelimiter, + byte[] _byte, + Integer integer, + Integer int32, + Long int64, + Float _float, + String string, + byte[] binary, + LocalDate date, + DateTime dateTime, + String password, + String paramCallback); + + /** + * @see FakeApi#testEnumParameters + */ + ResponseEntity testEnumParameters(List enumFormStringArray, + String enumFormString, + List enumHeaderStringArray, + String enumHeaderString, + List enumQueryStringArray, + String enumQueryString, + Integer enumQueryInteger, + Double enumQueryDouble); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..295109d7fc4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..7d48cfb31c9 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,147 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.POST) + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Pet not found", response = Void.class), + @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.PUT) + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + consumes = { "application/x-www-form-urlencoded" }, + method = RequestMethod.POST) + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" }, + method = RequestMethod.POST) + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..6eb175b89f0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class PetApiController implements PetApi { + private final PetApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + PetApiController(PetApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.addPet(body); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return delegate.deletePet(petId, apiKey); + } + + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return delegate.findPetsByStatus(status); + } + + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return delegate.findPetsByTags(tags); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return delegate.getPetById(petId); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.updatePet(body); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return delegate.updatePetWithForm(petId, name, status); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return delegate.uploadFile(petId, additionalMetadata, file); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java new file mode 100644 index 00000000000..f028b3c2e77 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java @@ -0,0 +1,66 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link PetApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link PetApiController}. + */ + +public interface PetApiDelegate { + + /** + * @see PetApi#addPet + */ + ResponseEntity addPet(Pet body); + + /** + * @see PetApi#deletePet + */ + ResponseEntity deletePet(Long petId, + String apiKey); + + /** + * @see PetApi#findPetsByStatus + */ + ResponseEntity> findPetsByStatus(List status); + + /** + * @see PetApi#findPetsByTags + */ + ResponseEntity> findPetsByTags(List tags); + + /** + * @see PetApi#getPetById + */ + ResponseEntity getPetById(Long petId); + + /** + * @see PetApi#updatePet + */ + ResponseEntity updatePet(Pet body); + + /** + * @see PetApi#updatePetWithForm + */ + ResponseEntity updatePetWithForm(Long petId, + String name, + String status); + + /** + * @see PetApi#uploadFile + */ + ResponseEntity uploadFile(Long petId, + String additionalMetadata, + MultipartFile file); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..f5526de9862 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,64 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = { "application/json" }, + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..6215ded3540 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,52 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class StoreApiController implements StoreApi { + private final StoreApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + StoreApiController(StoreApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return delegate.deleteOrder(orderId); + } + + public ResponseEntity> getInventory() { + // do some magic! + return delegate.getInventory(); + } + + public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return delegate.getOrderById(orderId); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return delegate.placeOrder(body); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java new file mode 100644 index 00000000000..ddf2901926a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -0,0 +1,40 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link StoreApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link StoreApiController}. + */ + +public interface StoreApiDelegate { + + /** + * @see StoreApi#deleteOrder + */ + ResponseEntity deleteOrder(String orderId); + + /** + * @see StoreApi#getInventory + */ + ResponseEntity> getInventory(); + + /** + * @see StoreApi#getOrderById + */ + ResponseEntity getOrderById(Long orderId); + + /** + * @see StoreApi#placeOrder + */ + ResponseEntity placeOrder(Order body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..c31b5a143ee --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,101 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.PUT) + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..7cb74a3e172 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,74 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + + + +@Controller +public class UserApiController implements UserApi { + private final UserApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + UserApiController(UserApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.createUser(body); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithArrayInput(body); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithListInput(body); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.deleteUser(username); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.getUserByName(username); + } + + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return delegate.loginUser(username, password); + } + + public ResponseEntity logoutUser() { + // do some magic! + return delegate.logoutUser(); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.updateUser(username, body); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java new file mode 100644 index 00000000000..7c2e86e1a95 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java @@ -0,0 +1,62 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link UserApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link UserApiController}. + */ + +public interface UserApiDelegate { + + /** + * @see UserApi#createUser + */ + ResponseEntity createUser(User body); + + /** + * @see UserApi#createUsersWithArrayInput + */ + ResponseEntity createUsersWithArrayInput(List body); + + /** + * @see UserApi#createUsersWithListInput + */ + ResponseEntity createUsersWithListInput(List body); + + /** + * @see UserApi#deleteUser + */ + ResponseEntity deleteUser(String username); + + /** + * @see UserApi#getUserByName + */ + ResponseEntity getUserByName(String username); + + /** + * @see UserApi#loginUser + */ + ResponseEntity loginUser(String username, + String password); + + /** + * @see UserApi#logoutUser + */ + ResponseEntity logoutUser(); + + /** + * @see UserApi#updateUser + */ + ResponseEntity updateUser(String username, + User body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java new file mode 100644 index 00000000000..d195523c1d3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java @@ -0,0 +1,16 @@ +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java new file mode 100644 index 00000000000..5658793e134 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -0,0 +1,40 @@ +package io.swagger.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + +@Configuration +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Swagger Petstore") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("","", "apiteam@swagger.io")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) + .build() + .directModelSubstitute(org.joda.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.joda.time.DateTime.class, java.util.Date.class) + .apiInfo(apiInfo()); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..f74f7d3d882 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..60aaf82231f --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,99 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Animal + */ + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..c2b0084d9cd --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; + +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..803eb69e16a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..bebc2470927 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..19464a99acd --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; + +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..94cb9977104 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..95bea570923 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..ba1ecfdb2b8 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..16c743e4f32 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..fcb2b0a8340 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..f8072688756 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; + +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..959b35e6b13 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; + +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..d8ac42c4872 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..d081e726855 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,240 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; + +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..6367fe81b0c --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,363 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.joda.time.DateTime; +import org.joda.time.LocalDate; + +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..55817f8dd14 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(value = "") + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9ef30a045d0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..36106536c7b --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.joda.time.DateTime; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private String uuid = null; + + @JsonProperty("dateTime") + private DateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(DateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public DateTime getDateTime() { + return dateTime; + } + + public void setDateTime(DateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..09ad4d0d60e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..82f447004ee --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,120 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..884a45c598e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..aa31ac8d79a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,144 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(value = "") + public Integer get123Number() { + return _123Number; + } + + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..9424f7a4b5e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; + +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..2863c127f60 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,224 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.joda.time.DateTime; + +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private DateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(DateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public DateTime getShipDate() { + return shipDate; + } + + public void setShipDate(DateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..0abc3d063b5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..823d25e05a0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,237 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..76d529c087a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..2cdc99de90e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..846812a5031 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..52c5fff826e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java @@ -0,0 +1,235 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/resources/application.properties b/samples/server/petstore/springboot-delegate/src/main/resources/application.properties new file mode 100644 index 00000000000..a2ef8627027 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/resources/application.properties @@ -0,0 +1,5 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index 6fb7235d18b..7a9f9fc2920 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -1,9 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; -import org.joda.time.LocalDate; import java.math.BigDecimal; +import io.swagger.model.Client; import org.joda.time.DateTime; +import org.joda.time.LocalDate; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; @@ -22,7 +22,7 @@ import java.util.List; @Api(value = "fake", description = "the fake API") public interface FakeApi { - @ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) @RequestMapping(value = "/fake", @@ -58,7 +58,7 @@ public interface FakeApi { @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback); - @ApiOperation(value = "To test enum parameters", notes = "", response = Void.class, tags={ "fake", }) + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid request", response = Void.class), @ApiResponse(code = 404, message = "Not found", response = Void.class) }) @@ -72,7 +72,7 @@ public interface FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index f4adae4ec88..0e2279b664e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -1,9 +1,9 @@ package io.swagger.api; -import io.swagger.model.Client; -import org.joda.time.LocalDate; import java.math.BigDecimal; +import io.swagger.model.Client; import org.joda.time.DateTime; +import org.joda.time.LocalDate; import io.swagger.annotations.*; @@ -24,6 +24,8 @@ import java.util.List; @Controller public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -53,7 +55,7 @@ public class FakeApiController implements FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 5b69114555e..7d48cfb31c9 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index 695d4cc2386..ee499f0d27f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -1,8 +1,8 @@ package io.swagger.api; -import io.swagger.model.Pet; -import io.swagger.model.ModelApiResponse; import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import io.swagger.annotations.*; @@ -23,6 +23,8 @@ import java.util.List; @Controller public class PetApiController implements PetApi { + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java index bd582ae1a94..2cc8b49c41e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java @@ -22,6 +22,8 @@ import java.util.List; @Controller public class StoreApiController implements StoreApi { + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index 44a359c309d..c31b5a143ee 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; import org.springframework.http.ResponseEntity; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java index a5a6d4d4505..81d3dabb762 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java @@ -1,7 +1,7 @@ package io.swagger.api; -import io.swagger.model.User; import java.util.List; +import io.swagger.model.User; import io.swagger.annotations.*; @@ -22,6 +22,8 @@ import java.util.List; @Controller public class UserApiController implements UserApi { + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java index de739ed501c..60aaf82231f 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java @@ -3,6 +3,8 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..94cb9977104 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..16c743e4f32 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java index dc00d569c7e..d081e726855 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; /** * EnumTest @@ -116,6 +117,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -170,6 +174,24 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -182,12 +204,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @Override @@ -198,6 +221,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java index 8d3cd2bec93..6367fe81b0c 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java @@ -60,8 +60,8 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ @ApiModelProperty(value = "") @@ -80,8 +80,8 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ @ApiModelProperty(value = "") diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..0abc3d063b5 --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + From ccb33850814eb00fc809f365dfd582c5bbd91643 Mon Sep 17 00:00:00 2001 From: Albert Morlan Date: Thu, 19 Jan 2017 04:07:58 -0600 Subject: [PATCH 269/269] Set embedded templates directory when generating Javascript code (#4585) --- .../languages/JavascriptClientCodegen.java | 2 +- .../petstore/javascript-promise/README.md | 4 +- .../javascript-promise/docs/Capitalization.md | 13 ++ .../javascript-promise/docs/ClassModel.md | 8 ++ .../javascript-promise/docs/FakeApi.md | 6 +- .../javascript-promise/src/api/FakeApi.js | 2 + .../petstore/javascript-promise/src/index.js | 16 ++- .../src/model/Capitalization.js | 120 ++++++++++++++++++ .../src/model/ClassModel.js | 80 ++++++++++++ .../test/model/Capitalization.spec.js | 95 ++++++++++++++ .../test/model/ClassModel.spec.js | 65 ++++++++++ samples/client/petstore/javascript/README.md | 4 +- .../javascript/docs/Capitalization.md | 13 ++ .../petstore/javascript/docs/ClassModel.md | 8 ++ .../petstore/javascript/docs/FakeApi.md | 6 +- .../petstore/javascript/src/api/FakeApi.js | 2 + .../client/petstore/javascript/src/index.js | 16 ++- .../javascript/src/model/Capitalization.js | 120 ++++++++++++++++++ .../javascript/src/model/ClassModel.js | 80 ++++++++++++ .../test/model/Capitalization.spec.js | 95 ++++++++++++++ .../javascript/test/model/ClassModel.spec.js | 65 ++++++++++ 21 files changed, 809 insertions(+), 11 deletions(-) create mode 100644 samples/client/petstore/javascript-promise/docs/Capitalization.md create mode 100644 samples/client/petstore/javascript-promise/docs/ClassModel.md create mode 100644 samples/client/petstore/javascript-promise/src/model/Capitalization.js create mode 100644 samples/client/petstore/javascript-promise/src/model/ClassModel.js create mode 100644 samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js create mode 100644 samples/client/petstore/javascript-promise/test/model/ClassModel.spec.js create mode 100644 samples/client/petstore/javascript/docs/Capitalization.md create mode 100644 samples/client/petstore/javascript/docs/ClassModel.md create mode 100644 samples/client/petstore/javascript/src/model/Capitalization.js create mode 100644 samples/client/petstore/javascript/src/model/ClassModel.js create mode 100644 samples/client/petstore/javascript/test/model/Capitalization.spec.js create mode 100644 samples/client/petstore/javascript/test/model/ClassModel.spec.js diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 4b345375051..8b68dcdbd16 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -84,7 +84,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo modelTestTemplateFiles.put("model_test.mustache", ".js"); apiTemplateFiles.put("api.mustache", ".js"); apiTestTemplateFiles.put("api_test.mustache", ".js"); - templateDir = "Javascript"; + embeddedTemplateDir = templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; modelDocTemplateFiles.put("model_doc.mustache", ".md"); diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index 4a43f5c06e5..994797b512c 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -6,7 +6,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build package: class io.swagger.codegen.languages.JavascriptClientCodegen +- Build package: io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -105,8 +105,10 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) + - [SwaggerPetstore.Capitalization](docs/Capitalization.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.ClassModel](docs/ClassModel.md) - [SwaggerPetstore.Client](docs/Client.md) - [SwaggerPetstore.Dog](docs/Dog.md) - [SwaggerPetstore.EnumArrays](docs/EnumArrays.md) diff --git a/samples/client/petstore/javascript-promise/docs/Capitalization.md b/samples/client/petstore/javascript-promise/docs/Capitalization.md new file mode 100644 index 00000000000..c223a4ee982 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Capitalization.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/ClassModel.md b/samples/client/petstore/javascript-promise/docs/ClassModel.md new file mode 100644 index 00000000000..bf8343b84b3 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/ClassModel.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript-promise/docs/FakeApi.md b/samples/client/petstore/javascript-promise/docs/FakeApi.md index b7f35a52ab6..5d825199ebf 100644 --- a/samples/client/petstore/javascript-promise/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); @@ -136,6 +138,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); @@ -149,7 +153,7 @@ var opts = { 'enumHeaderString': "-efg", // String | Header parameter enum test (string) 'enumQueryStringArray': ["enumQueryStringArray_example"], // [String] | Query parameter enum test (string array) 'enumQueryString': "-efg", // String | Query parameter enum test (string) - 'enumQueryInteger': 3.4, // Number | Query parameter enum test (double) + 'enumQueryInteger': 56, // Number | Query parameter enum test (double) 'enumQueryDouble': 1.2 // Number | Query parameter enum test (double) }; apiInstance.testEnumParameters(opts).then(function() { diff --git a/samples/client/petstore/javascript-promise/src/api/FakeApi.js b/samples/client/petstore/javascript-promise/src/api/FakeApi.js index cd977007506..623fb1d191e 100644 --- a/samples/client/petstore/javascript-promise/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise/src/api/FakeApi.js @@ -47,6 +47,7 @@ /** + * To test \"client\" model * To test \"client\" model * @param {module:model/Client} body client model * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with data of type {@link module:model/Client} @@ -164,6 +165,7 @@ /** + * To test enum parameters * To test enum parameters * @param {Object} opts Optional parameters * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index 5f524f02ea3..caff166e82c 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Capitalization', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Capitalization'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Capitalization, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -94,6 +94,11 @@ * @property {module:model/ArrayTest} */ ArrayTest: ArrayTest, + /** + * The Capitalization model constructor. + * @property {module:model/Capitalization} + */ + Capitalization: Capitalization, /** * The Cat model constructor. * @property {module:model/Cat} @@ -104,6 +109,11 @@ * @property {module:model/Category} */ Category: Category, + /** + * The ClassModel model constructor. + * @property {module:model/ClassModel} + */ + ClassModel: ClassModel, /** * The Client model constructor. * @property {module:model/Client} diff --git a/samples/client/petstore/javascript-promise/src/model/Capitalization.js b/samples/client/petstore/javascript-promise/src/model/Capitalization.js new file mode 100644 index 00000000000..84480fa0d40 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Capitalization.js @@ -0,0 +1,120 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Capitalization = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Capitalization model module. + * @module model/Capitalization + * @version 1.0.0 + */ + + /** + * Constructs a new Capitalization. + * @alias module:model/Capitalization + * @class + */ + var exports = function() { + var _this = this; + + + + + + + + }; + + /** + * Constructs a Capitalization from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Capitalization} obj Optional instance to populate. + * @return {module:model/Capitalization} The populated Capitalization instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('smallCamel')) { + obj['smallCamel'] = ApiClient.convertToType(data['smallCamel'], 'String'); + } + if (data.hasOwnProperty('CapitalCamel')) { + obj['CapitalCamel'] = ApiClient.convertToType(data['CapitalCamel'], 'String'); + } + if (data.hasOwnProperty('small_Snake')) { + obj['small_Snake'] = ApiClient.convertToType(data['small_Snake'], 'String'); + } + if (data.hasOwnProperty('Capital_Snake')) { + obj['Capital_Snake'] = ApiClient.convertToType(data['Capital_Snake'], 'String'); + } + if (data.hasOwnProperty('SCA_ETH_Flow_Points')) { + obj['SCA_ETH_Flow_Points'] = ApiClient.convertToType(data['SCA_ETH_Flow_Points'], 'String'); + } + if (data.hasOwnProperty('ATT_NAME')) { + obj['ATT_NAME'] = ApiClient.convertToType(data['ATT_NAME'], 'String'); + } + } + return obj; + } + + /** + * @member {String} smallCamel + */ + exports.prototype['smallCamel'] = undefined; + /** + * @member {String} CapitalCamel + */ + exports.prototype['CapitalCamel'] = undefined; + /** + * @member {String} small_Snake + */ + exports.prototype['small_Snake'] = undefined; + /** + * @member {String} Capital_Snake + */ + exports.prototype['Capital_Snake'] = undefined; + /** + * @member {String} SCA_ETH_Flow_Points + */ + exports.prototype['SCA_ETH_Flow_Points'] = undefined; + /** + * Name of the pet + * @member {String} ATT_NAME + */ + exports.prototype['ATT_NAME'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/ClassModel.js b/samples/client/petstore/javascript-promise/src/model/ClassModel.js new file mode 100644 index 00000000000..bd438f9c239 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/ClassModel.js @@ -0,0 +1,80 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ClassModel = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The ClassModel model module. + * @module model/ClassModel + * @version 1.0.0 + */ + + /** + * Constructs a new ClassModel. + * Model for testing model with \"_class\" property + * @alias module:model/ClassModel + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a ClassModel from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ClassModel} obj Optional instance to populate. + * @return {module:model/ClassModel} The populated ClassModel instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('_class')) { + obj['_class'] = ApiClient.convertToType(data['_class'], 'String'); + } + } + return obj; + } + + /** + * @member {String} _class + */ + exports.prototype['_class'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js b/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js new file mode 100644 index 00000000000..f1aa695c3fd --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Capitalization(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Capitalization', function() { + it('should create an instance of Capitalization', function() { + // uncomment below and update the code to test Capitalization + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be.a(SwaggerPetstore.Capitalization); + }); + + it('should have the property smallCamel (base name: "smallCamel")', function() { + // uncomment below and update the code to test the property smallCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalCamel (base name: "CapitalCamel")', function() { + // uncomment below and update the code to test the property capitalCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property smallSnake (base name: "small_Snake")', function() { + // uncomment below and update the code to test the property smallSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalSnake (base name: "Capital_Snake")', function() { + // uncomment below and update the code to test the property capitalSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { + // uncomment below and update the code to test the property sCAETHFlowPoints + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { + // uncomment below and update the code to test the property ATT_NAME + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript-promise/test/model/ClassModel.spec.js b/samples/client/petstore/javascript-promise/test/model/ClassModel.spec.js new file mode 100644 index 00000000000..5ee2e49a0de --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/ClassModel.spec.js @@ -0,0 +1,65 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.ClassModel(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ClassModel', function() { + it('should create an instance of ClassModel', function() { + // uncomment below and update the code to test ClassModel + //var instane = new SwaggerPetstore.ClassModel(); + //expect(instance).to.be.a(SwaggerPetstore.ClassModel); + }); + + it('should have the property _class (base name: "_class")', function() { + // uncomment below and update the code to test the property _class + //var instane = new SwaggerPetstore.ClassModel(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index 69d3934db95..2687975e715 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -6,7 +6,7 @@ This SDK is automatically generated by the [Swagger Codegen](https://github.com/ - API version: 1.0.0 - Package version: 1.0.0 -- Build package: class io.swagger.codegen.languages.JavascriptClientCodegen +- Build package: io.swagger.codegen.languages.JavascriptClientCodegen ## Installation @@ -108,8 +108,10 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) + - [SwaggerPetstore.Capitalization](docs/Capitalization.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) + - [SwaggerPetstore.ClassModel](docs/ClassModel.md) - [SwaggerPetstore.Client](docs/Client.md) - [SwaggerPetstore.Dog](docs/Dog.md) - [SwaggerPetstore.EnumArrays](docs/EnumArrays.md) diff --git a/samples/client/petstore/javascript/docs/Capitalization.md b/samples/client/petstore/javascript/docs/Capitalization.md new file mode 100644 index 00000000000..c223a4ee982 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Capitalization.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + diff --git a/samples/client/petstore/javascript/docs/ClassModel.md b/samples/client/petstore/javascript/docs/ClassModel.md new file mode 100644 index 00000000000..bf8343b84b3 --- /dev/null +++ b/samples/client/petstore/javascript/docs/ClassModel.md @@ -0,0 +1,8 @@ +# SwaggerPetstore.ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + + diff --git a/samples/client/petstore/javascript/docs/FakeApi.md b/samples/client/petstore/javascript/docs/FakeApi.md index 17cd0e3da99..3b05c7158e0 100644 --- a/samples/client/petstore/javascript/docs/FakeApi.md +++ b/samples/client/petstore/javascript/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); @@ -142,6 +144,8 @@ null (empty response body) To test enum parameters +To test enum parameters + ### Example ```javascript var SwaggerPetstore = require('swagger_petstore'); @@ -155,7 +159,7 @@ var opts = { 'enumHeaderString': "-efg", // String | Header parameter enum test (string) 'enumQueryStringArray': ["enumQueryStringArray_example"], // [String] | Query parameter enum test (string array) 'enumQueryString': "-efg", // String | Query parameter enum test (string) - 'enumQueryInteger': 3.4, // Number | Query parameter enum test (double) + 'enumQueryInteger': 56, // Number | Query parameter enum test (double) 'enumQueryDouble': 1.2 // Number | Query parameter enum test (double) }; diff --git a/samples/client/petstore/javascript/src/api/FakeApi.js b/samples/client/petstore/javascript/src/api/FakeApi.js index 7e44e3c6e3a..c9f0fbdbf03 100644 --- a/samples/client/petstore/javascript/src/api/FakeApi.js +++ b/samples/client/petstore/javascript/src/api/FakeApi.js @@ -54,6 +54,7 @@ */ /** + * To test \"client\" model * To test \"client\" model * @param {module:model/Client} body client model * @param {module:api/FakeApi~testClientModelCallback} callback The callback function, accepting three arguments: error, data, response @@ -186,6 +187,7 @@ */ /** + * To test enum parameters * To test enum parameters * @param {Object} opts Optional parameters * @param {Array.} opts.enumFormStringArray Form parameter enum test (string array) diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 5f524f02ea3..caff166e82c 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Capitalization', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Capitalization'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Capitalization, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -94,6 +94,11 @@ * @property {module:model/ArrayTest} */ ArrayTest: ArrayTest, + /** + * The Capitalization model constructor. + * @property {module:model/Capitalization} + */ + Capitalization: Capitalization, /** * The Cat model constructor. * @property {module:model/Cat} @@ -104,6 +109,11 @@ * @property {module:model/Category} */ Category: Category, + /** + * The ClassModel model constructor. + * @property {module:model/ClassModel} + */ + ClassModel: ClassModel, /** * The Client model constructor. * @property {module:model/Client} diff --git a/samples/client/petstore/javascript/src/model/Capitalization.js b/samples/client/petstore/javascript/src/model/Capitalization.js new file mode 100644 index 00000000000..84480fa0d40 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Capitalization.js @@ -0,0 +1,120 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Capitalization = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Capitalization model module. + * @module model/Capitalization + * @version 1.0.0 + */ + + /** + * Constructs a new Capitalization. + * @alias module:model/Capitalization + * @class + */ + var exports = function() { + var _this = this; + + + + + + + + }; + + /** + * Constructs a Capitalization from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Capitalization} obj Optional instance to populate. + * @return {module:model/Capitalization} The populated Capitalization instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('smallCamel')) { + obj['smallCamel'] = ApiClient.convertToType(data['smallCamel'], 'String'); + } + if (data.hasOwnProperty('CapitalCamel')) { + obj['CapitalCamel'] = ApiClient.convertToType(data['CapitalCamel'], 'String'); + } + if (data.hasOwnProperty('small_Snake')) { + obj['small_Snake'] = ApiClient.convertToType(data['small_Snake'], 'String'); + } + if (data.hasOwnProperty('Capital_Snake')) { + obj['Capital_Snake'] = ApiClient.convertToType(data['Capital_Snake'], 'String'); + } + if (data.hasOwnProperty('SCA_ETH_Flow_Points')) { + obj['SCA_ETH_Flow_Points'] = ApiClient.convertToType(data['SCA_ETH_Flow_Points'], 'String'); + } + if (data.hasOwnProperty('ATT_NAME')) { + obj['ATT_NAME'] = ApiClient.convertToType(data['ATT_NAME'], 'String'); + } + } + return obj; + } + + /** + * @member {String} smallCamel + */ + exports.prototype['smallCamel'] = undefined; + /** + * @member {String} CapitalCamel + */ + exports.prototype['CapitalCamel'] = undefined; + /** + * @member {String} small_Snake + */ + exports.prototype['small_Snake'] = undefined; + /** + * @member {String} Capital_Snake + */ + exports.prototype['Capital_Snake'] = undefined; + /** + * @member {String} SCA_ETH_Flow_Points + */ + exports.prototype['SCA_ETH_Flow_Points'] = undefined; + /** + * Name of the pet + * @member {String} ATT_NAME + */ + exports.prototype['ATT_NAME'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/ClassModel.js b/samples/client/petstore/javascript/src/model/ClassModel.js new file mode 100644 index 00000000000..bd438f9c239 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/ClassModel.js @@ -0,0 +1,80 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.ClassModel = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The ClassModel model module. + * @module model/ClassModel + * @version 1.0.0 + */ + + /** + * Constructs a new ClassModel. + * Model for testing model with \"_class\" property + * @alias module:model/ClassModel + * @class + */ + var exports = function() { + var _this = this; + + + }; + + /** + * Constructs a ClassModel from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ClassModel} obj Optional instance to populate. + * @return {module:model/ClassModel} The populated ClassModel instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('_class')) { + obj['_class'] = ApiClient.convertToType(data['_class'], 'String'); + } + } + return obj; + } + + /** + * @member {String} _class + */ + exports.prototype['_class'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/test/model/Capitalization.spec.js b/samples/client/petstore/javascript/test/model/Capitalization.spec.js new file mode 100644 index 00000000000..f1aa695c3fd --- /dev/null +++ b/samples/client/petstore/javascript/test/model/Capitalization.spec.js @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Capitalization(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Capitalization', function() { + it('should create an instance of Capitalization', function() { + // uncomment below and update the code to test Capitalization + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be.a(SwaggerPetstore.Capitalization); + }); + + it('should have the property smallCamel (base name: "smallCamel")', function() { + // uncomment below and update the code to test the property smallCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalCamel (base name: "CapitalCamel")', function() { + // uncomment below and update the code to test the property capitalCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property smallSnake (base name: "small_Snake")', function() { + // uncomment below and update the code to test the property smallSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalSnake (base name: "Capital_Snake")', function() { + // uncomment below and update the code to test the property capitalSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { + // uncomment below and update the code to test the property sCAETHFlowPoints + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { + // uncomment below and update the code to test the property ATT_NAME + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/test/model/ClassModel.spec.js b/samples/client/petstore/javascript/test/model/ClassModel.spec.js new file mode 100644 index 00000000000..5ee2e49a0de --- /dev/null +++ b/samples/client/petstore/javascript/test/model/ClassModel.spec.js @@ -0,0 +1,65 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.ClassModel(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('ClassModel', function() { + it('should create an instance of ClassModel', function() { + // uncomment below and update the code to test ClassModel + //var instane = new SwaggerPetstore.ClassModel(); + //expect(instance).to.be.a(SwaggerPetstore.ClassModel); + }); + + it('should have the property _class (base name: "_class")', function() { + // uncomment below and update the code to test the property _class + //var instane = new SwaggerPetstore.ClassModel(); + //expect(instance).to.be(); + }); + + }); + +}));